view raw
Rawnly Rawnly - 5 months ago 46
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');

// Key
const key = "*************";
const freegeoip = "";

let latitude = 0,
longitude = 0 ;

// api url
const url = `${key}/${latitude},${longitude}`;

// initialize myData with the freegeoip datas
let myData = request({
url: '',
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


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


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