简体   繁体   English

如何在不覆盖文本的情况下在javascript中写入文本文件?

[英]How to write to text file in javascript without overwriting text?

Past research I've done on this topic says that this code:我过去在这个主题上所做的研究表明这段代码:

    const filestream = require('fs');
    for(let a = 0; a < 4; a++) {
        fs.writeFileSync('test.txt', 'test' + a + '\n', 'UTF-8', {'flags': 'a'});
    }

should output应该输出

test0测试0
test1测试1
test2测试2
test3测试3

to test.txt.测试.txt。 However, all I'm seeing is test3, indicating that each write to the file is overwriting all existing text.但是,我所看到的只是 test3,表明对文件的每次写入都会覆盖所有现有文本。 Despite my use of the 'a' flag.尽管我使用了“a”标志。 What's going on here?这里发生了什么?

我认为您应该为此使用另一个功能,您可以尝试以下操作吗?

fs.appendFileSync('test.txt', 'test' + a + '\n');

fs.writeFileSync() replaces the entire contents of the file with your new content. fs.writeFileSync()用您的新内容替换文件的全部内容。 It does not append content to the end.它不会将内容附加到末尾。 There are multiple ways to append to the end of a file.有多种方法可以附加到文件的末尾。

The simplest mechanism is fs.appendFileSync() and that will work for you, but it isn't very efficient to call that in a loop because internally, fs.appendfileSync() will call fs.openSync() , fs.writeSync() and the fs.closeSync() for each time through the loop.最简单的机制是fs.appendFileSync() ,它对你fs.appendFileSync() ,但在循环中调用它不是很有效,因为在内部, fs.appendfileSync()将调用fs.openSync()fs.writeSync()以及每次循环的fs.closeSync()

It would be better to open the file once, do all your writing and then close the file.最好打开文件一次,写完所有内容,然后关闭文件。

const fs = require('fs');

const fd = fs.openSync('temp.txt', 'w');
for (let a = 0; a < 4; a++) {
    fs.writeSync(fd, 'test' + a + '\n', 'utf-8');
}
fs.closeSync(fd);

Or, you can collect your data and then write it all at once:或者,您可以收集数据,然后一次性写入所有数据:

let data = [];
for (let a = 0; a < 4; a++) {
    data.push('test' + a + '\n');
}    
fs.writeFileSync('temp.txt', data.join(''), 'utf-8');

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

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