Javascript 向Node.js中的文件追加行会导致内容以随机顺序写入
我写了这段代码,基本上标题行并不总是在第一个位置。它随机转到第二行或第三行。请帮忙,我试过很多次了Javascript 向Node.js中的文件追加行会导致内容以随机顺序写入,javascript,node.js,file,asynchronous,Javascript,Node.js,File,Asynchronous,我写了这段代码,基本上标题行并不总是在第一个位置。它随机转到第二行或第三行。请帮忙,我试过很多次了 var fs = require('fs'); const path = './Output.csv'; if (fs.existsSync(path)){ fs.unlinkSync(path); } fs.closeSync(fs.openSync(path, 'w')); fs.appendFile(path,'SamAccountName,Sid \n', function (e
var fs = require('fs');
const path = './Output.csv';
if (fs.existsSync(path)){
fs.unlinkSync(path);
}
fs.closeSync(fs.openSync(path, 'w'));
fs.appendFile(path,'SamAccountName,Sid \n', function (err) {
if (err) return console.log(err);
});
for (i = 0; i < array_Sid_SidHistory_Full.length; i++) {
fs.appendFile(path, array_Sid_SidHistory_Full[i]+"\n" , function (err) {
if (err) return console.log(err);
});
}
有时,输出是这样的:
a,S-1-5-21-541258428-755705122-2342590333-8456
b、 S-1-5-21-541258428-755705122-2342590333-6683
SamAccountName,Sid
c、 S-1-5-21-541258428-755705122-2342590333-8459
d、 S-1-5-21-541258428-755705122-2342590333-3413
e、 S-1-5-21-541258428-755705122-2342590333-1140
f、 S-1-5-21-541258428-755705122-2342590333-17241
或
a,S-1-5-21-541258428-755705122-2342590333-8456
SamAccountName,Sid
b、 S-1-5-21-541258428-755705122-2342590333-6683
c、 S-1-5-21-541258428-755705122-2342590333-8459
d、 S-1-5-21-541258428-755705122-2342590333-3413
e、 S-1-5-21-541258428-755705122-2342590333-1140
f、 S-1-5-21-541258428-755705122-2342590333-17241
根据节点文档,将数据异步附加到文件中。这意味着代码在文件资源上有一个属性,回调执行的任意顺序最终决定了输出(节点在引擎盖下分派线程来处理这些回调)
确保顺序订购可以使用。许多节点fs
函数都有一个同步版本。或者,您可以在执行下一个附加之前等待每个异步调用的解析,但在本例中这似乎有点像鞋钉
假设文件适合内存,您还可以使用连接构建表示文件内容的整个字符串,然后通过调用
fs.writeFile
(或fs.appendFile
)将整个文件转储到磁盘如果需要执行进一步的操作,请使用回调。使用流将具有最低的内存占用:
function writeCSV(stream, data) {
while (data.length > 0) {
// Process the data backwards assuming the CSV header is the last element.
// Working backwards and popping the elements off the end allows us to avoid
// maintaining an index but mutates the original array.
if (!stream.write(`${data.pop()}\n`)) {
// Wait for data to drain before writing more.
stream.once('drain', () => writeCSV(stream, data));
return;
}
}
stream.end();
}
// Open the write stream and watch for errors and completion.
const stream = fs.createWriteStream(path);
stream.on('error', (err) => console.error(err));
stream.on('finish', () => console.log(`Completed writing to: ${path}`));
// Push the header onto the end of the data and write the file.
array_Sid_SidHistory_Full.push('SamAccountName,Sid');
writeCSV(stream, array_Sid_SidHistory_Full);
但是在内存中构造文件肯定更简单(在@ggorlen的回答中描述):
与使用fs.appendFile
相比,这两种方法的开销更小,因为文件在写入过程中只打开和关闭一次,而不是针对每行数据打开和关闭
const data = `SamAccountName,Sid\n${array_Sid_SidHistory_Full.join('\n')}\n`;
fs.writeFile(path, data, (err) => {
if (err) {
console.error(err)
} else {
console.log(`Completed writing to: ${path}`)
}
});