Node.js FS保存对象

Node.js FS saving object

我收到了这个 JSON 客户 API

{ COD:'100', ATD: '838', PAG: '246', VENC: '2017-01-27 00:00:00', }

我将这个 JSON 保存在 var 对象中,然后我尝试像这样保存这个变量对象:

fs.writeFile("boleto.txt", object, 'utf8', function(err){
        if(err){
            console.log(err);
        } else {
            console.log("Log salvo");
        }
    });

但是BOLETO.TXT中的结果是这样的:[object Object]

我需要这个:

COD: '100', ATD: '838', PAG: '246', VENC: '2017-01-27 00:00:00'

我做错了什么?

ps.: 当我调用 console.log(object) 时,日志是正确的。

//This will work JSON.stringify, JSON.stringify converts json object into a string that can be writable in text file instead of [object object]
fs.writeFile("boleto.txt", JSON.stringify(object), 'utf8', function(err){
        if(err){
            console.log(err);
        } else {
            console.log("Log salvo");
        }
    });

您需要先将 JSON 字符串化。

fs.writeFile("boleto.txt", JSON.stringify(object, null, 2), 'utf8', function(err){
    if(err){
        console.log(err);
    } else {
        console.log("Log salvo");
    }
});

JSON.stringify(object, null, 2) 允许您跳过 key/values、 之间的行,即 具有更高的可读性 JSON.