【问题标题】:Writing into file in nodejs using fs.writefilesync使用 fs.writefilesync 在 nodejs 中写入文件
【发布时间】: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);

【问题讨论】:

标签: javascript node.js file


【解决方案1】:

fs.writeFileSync 的默认模式是覆盖整个文件。正如@Bartosz Gościński 提到的,您可以使用appendFileSync 或在fileWriteSync 中设置option 以附加新文本:

fs.writeFileSync('notes.json', originalNoteString, {flag: 'a'});

更多不同的标志值见here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    相关资源
    最近更新 更多