javascript 写入文本文件而不覆盖 fs 节点 js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17324797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:54:17  来源:igfitidea点击:

Write in a text file without overwriting in fs node js

javascriptnode.js

提问by dardar.moh

How I can add text in my file but without overwriting the old text. I use the module fs (node js)

如何在我的文件中添加文本但不覆盖旧文本。我使用模块 fs(节点 js)

I tried this code but it doesn't work.

我试过这段代码,但它不起作用。

fs.writeFileSync("file.txt", 'Text', "UTF-8",{'flags': 'w+'});

any suggestion and Thanks.

任何建议和谢谢。

采纳答案by Prisoner

Check the flags here: http://nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback- you are currently using w+which:

检查这里的标志:http: //nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback- 您当前使用的w+是:

'w+' - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).

'w+' - 打开文件进行读写。该文件被创建(如果它不存在)或被截断(如果它存在)。

You should use ainstead:

你应该使用a

'a' - Open file for appending. The file is created if it does not exist.

'ax' - Like 'a' but opens the file in exclusive mode.

'a+' - Open file for reading and appending. The file is created if it does not exist.

'ax+' - Like 'a+' but opens the file in exclusive mode.

'a' - 打开文件进行追加。如果文件不存在,则创建该文件。

'ax' - 类似于 'a',但以独占模式打开文件。

'a+' - 打开文件进行读取和追加。如果文件不存在,则创建该文件。

'ax+' - 与 'a+' 类似,但以独占模式打开文件。

回答by Doris Hernandez

Use fs.appendFile, that will just append the new information!

使用 fs.appendFile,它只会追加新信息!

fs.appendFile("file.txt", 'Text',function(err){
if(err) throw err;
console.log('IS WRITTEN')
});