Rawnly Rawnly - 12 days ago 8
Ajax Question

NodeJs: can't write a file

I'm new in node, for practice i thought to develop a weather commandline application, but i found a problem with ajax request, i'm usually to use $.ajax of jquery but it doesn't works, ( I've tried to require jquery ). I've solved this problem with another module.

Now the problem is: when i try to print json information on the coords.json and next read it with read-json module there are some "\" & "\n" everywhere in the string, i've tried to replace it with regex and fs module but it doesn't re-write the file... why?

Here the full code:

// index.js
// modules
const program = require('commander');
const clear = require('clear');
const chalk = require('chalk');
const request = require('ajax-request');
const fs = require('fs');

const json = require('read-data').json;
const writeJson = require('write-json');

// Forecast.io Key
const key = "*************";
const freegeoip = "http://freegeoip.net/json/";

let latitude = 0,
longitude = 0 ;

// forecast.io api url
const url = `https://api.darksky.net/forecast/${key}/${latitude},${longitude}`;

// initialize myData with the freegeoip datas
let myData = request({
url: 'http://freegeoip.net/json/',
method: 'GET',
data: {
format: 'json'
},
}, function(err, res, body) {
writeJson('test.json', body, function(err) {
if (err) console.log(err);
});
});

fs.readFile('test.json', 'utf8', function (err,data) {
let result = data.replace(/[\\~#%&*<>?|\-]/g, '');
fs.writeFile('test.json', result, 'utf8', function (err) {
if (err) return console.log(err);
// if i do this is normal json
// console.log(result)
});

});


and the output in the file is:

// coords.json

"{\"ip\":\"**.**.**.**\",\"country_code\":\"IT\",\"country_name\":\"Italy\",\"region_code\":\"62\",\"region_name\":\"Latium\",\"city\":\"Rome\",\"zip_code\":\"00119\",\"time_zone\":\"Europe/Rome\",\"latitude\":**.*,\"longitude\":**.**\"metro_code\":0}\n"


but if i print it in console it's normal...

Answer

I really recommend that you use JSON.parse. It will parse your json and put it into a variable you can use:

fs.readFile('test.json', 'utf8', function (err,data) {  
    data = JSON.parse(data); // Yay you can use anything from the JSON
}