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

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 .

    评论

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题