简体   繁体   English

fs.write json文件以捕获并保存流json文件

[英]fs.write json file to capture and save streaming json file

I want json stream stored in text file. 我想将json流存储在文本文件中。 When running the node server, the json file isn't appended to the json.txt file. 运行节点服务器时,json文件不会附加到json.txt文件中。 What am I missing? 我想念什么? Am new to to node, so be gentle.. 是Node的新手,所以要保持柔和。

Here is a code chunk I expect to capture the json content: 这是我希望捕获json内容的代码块:

var fs = require('fs');
fs.writeFile("json.txt",{encoding:"utf8"}, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});

The issue is you aren't using the correct parameters. 问题是您使用的参数不正确。 When calling fs.writeFile it expects a string for the filename , a buffer or string for the content , an object for the options and a callback function . 调用fs.writeFile它要求文件名使用字符串,内容使用缓冲区或字符串, 选项使用对象以及回调函数 What it looks like you're doing is sending the options as the second parameter when it expects a buffer or a string. 看起来您正在做的是在需要缓冲区或字符串时将选项作为第二个参数发送。 Correction below; 更正如下;

var fs = require('fs');
fs.writeFile("json.txt", JSON.stringify({some: object}), {encoding:"utf8"}, function(err) {
    if(err) {
        console.log(err);
    } else {
        console.log("The file was saved!");
    }
});

You can replace the JSON.stringify part with some plain text if you wanted to, but you specified JSON in your question so I assumed you wanted to store some object in a file 您可以根据JSON.stringify用一些纯文本替换JSON.stringify部分,但是您在问题中指定了JSON,所以我假设您想在文件中存储一些对象

Source (NodeJS documentation) 来源 (NodeJS文档)

EDIT: The links to other questions in the comments may be more relevant if you want to add new lines to the end of the file and not completely overwrite the old one. 编辑:如果您想在文件末尾添加新行而不完全覆盖旧行,则注释中其他问题的链接可能更相关。 However I made the assumption that fs.writeFile was the intended function. 但是,我假设fs.writeFile是预期的功能。 If that wasn't the intention, those other questions will help a lot more 如果这不是故意的,那么其他问题将大有帮助

UPDATE: 更新:

It seems the issue was the fact that the body wasn't being parsed, so when the POST request was going through, Node didn't have the request body. 似乎问题在于未解析主体,因此在执行POST请求时,Node没有请求主体。 To alleviate this, during the express configuration, the following code is needed: 为了减轻这种情况,在快速配置期间,需要以下代码:

var bodyParser = require('body-parser');
app.use(bodyParser.json());

Uses the npm module body-parser . 使用npm模块body-parser This will convert the JSON body to a JavaScript object, and it is accessible via req.body . 这会将JSON主体转换为JavaScript对象,并且可以通过req.body访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM