Gre*_*reg -3 javascript json node.js
这可能是我错过了一些荒谬的东西,但当我添加object到我的json文件中时,NodeJs它会在文件的末尾添加它(显然是?)]
var file = './data/questions.json';
fs.appendFile(file, ', ' + JSON.stringify(req.body), function (err) {
console.log(err);
});
Run Code Online (Sandbox Code Playgroud)
结果是这样的:
[
{'id':1, 'name':'Tom'}
], {'id':2, 'name':'Jerry'}
Run Code Online (Sandbox Code Playgroud)
如果文件中已经有数组,那么你需要的是:
var file = './data/questions.json';
// get the contents of the file
var fileContents = do_something_to_get_contents;
// convert to js object
fileContents = JSON.parse(fileContents);
// push the array
fileContents = fileContents.push(req.body);
// update the file contents by stringify
fs.replaceFile(file, JSON.stringify(fileContents), function (err) {
console.log(err);
});
Run Code Online (Sandbox Code Playgroud)
我在Node JS中不是很好.所以我假设以下内容:
do_something_to_get_contents 获取文件内容.replaceFile 将此替换为将新内容写入文件的函数.| 归档时间: |
|
| 查看次数: |
135 次 |
| 最近记录: |