local-host 2016-11-26 01:19 采纳率: 100%
浏览 97

NodeJ:无法写入文件

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 "\" & " " 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}
"

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

  • 写回答

2条回答 默认 最新

  • weixin_33682790 2016-11-26 01:29
    关注

    The \ are there to escape the quotes so that they don't end the string. They shouldn't affect anything, and are actually necessary. Have you tried it without the regex? That could be breaking things if it actually removes the .

    评论

报告相同问题?