Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 向Node.js中的文件追加行会导致内容以随机顺序写入_Javascript_Node.js_File_Asynchronous - Fatal编程技术网

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}`)
    }
});