fs.appendFile不按顺序追加数据?

以下代码所做的是从文件夹中取几个文本文件并将其附加到文件中:

#!/usr/bin/env node 'use strict' const fs = require('fs') , input = process.argv[2] if (process.argv.length < 3) { console.log('Usage: node ' + process.argv[1] + ' FILENAME') process.exit(1) } fs.readdir(__dirname + `/${input}/`, (err, files) => { if (err) { return } files.forEach((file, index) => { fs.readFile(__dirname + `/${input}/` + file, 'utf8', (err, data) => { let result if (err) { console.log(err) } if (index == files.length - 1) { result = `${data}` } else { result = `${data}\n` } fs.appendFile("merged.txt", result, (err) => { if (err) { console.log(err) } else { console.log(result) } }) }) }) }) 

假设我有一个名为docs的文件夹,里面有doc1.txt,doc2.txt,doc3.txt分别with the content ## Doc 1,## Doc 2和## Doc 3 respectively. The code would produce a single file called respectively. The code would produce a single file called merged.txt的respectively. The code would produce a single file called ,其内容如下:

 ## Doc 1 ## Doc 2 ## Doc 3 

它工作正常。 但有时候这个顺序是错误的。 我会得到像这样的东西:

 ## Doc 1 ## Doc 3 ## Doc 2 

特别是当有很多文件。

我如何修改代码来防止这个问题?

您可以将fs.appendFile更改为fs.appendFileSync (快而脏,但不是最好的解决scheme),或者可以使用async模块的eachSeries方法以eachSeries方式运行事件( https://www.npmjs.com/package/ async#eachSeries )。