【发布时间】:2019-02-22 20:36:20
【问题描述】:
我正在尝试使用 fs.writeFileSync('notes.json', originalNoteString) 写入文件。当我第一次运行程序时,它正在附加,但是当我第二次运行程序时,它不再附加。任何人都可以帮助我这里发生了什么。
const fs = require('fs');
let orginalNote = {
title: 'sometitle',
body: 'somebody'
}
let originalNoteString = JSON.stringify(orginalNote);
fs.writeFileSync('notes.json', originalNoteString);
let noteString = fs.readFileSync('notes.json');
let note = JSON.parse(noteString);
console.log(typeof note);
console.log(note.title);
【问题讨论】:
-
writeFileSync默认会覆盖文件内容。对于附加,您应该使用appendFileSyncnodejs.org/api/fs.html#fs_fs_appendfilesync_path_data_options -
谢谢@BartoszGościński
标签: javascript node.js file