我正在尝试编写读取文件的代码,计算其中的行数,然后在开头添加另一行,该行的编号。基本上就像一个索引。问题是 fs.appendFile() 在 fs.readFile() 完成之前开始运行,但我不确定为什么。有什么我做错了吗?
我的代码:
fs.readFile('list.txt', 'utf-8', (err, data) => {
if (err) throw err;
lines = data.split(/\r\n|\r|\n/).length - 1;
console.log("Im supposed to run first");
});
console.log("Im supposed to run second");
fs.appendFile('list.txt', '[' + lines + ']' + item + '\n', function(err) {
if (err) throw err;
console.log('List updated!');
fs.readFile('list.txt', 'utf-8', (err, data) => {
if (err) throw err;
// Converting Raw Buffer dto text
// data using tostring function.
message.channel.send('List was updated successfully! New list: \n' + data.toString());
console.log(data);
});
});
我的输出:
Im supposed to run second
List updated!
Im supposed to run first
[0]first item