我正在尝试编写读取文件的代码,计算其中的行数,然后在开头添加另一行的编号。基本上,就像一个索引。问题是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

发布于 2019-12-06 03:40:34
目前,您正在使用readFile和appendFile。这两个函数都是异步的,将同时运行,并在完成时返回。
如果您想同步运行这些文件,您可以使用fs.readFileSync和fs.appendFileSync方法来同步读取和附加到这些文件。
因此,如下所示:
const readFileData = fs.readFileSync("list.txt");
fs.appendFileSync('list.txt', '[' + lines + ']' + item + '\n');将运行第一行代码,然后运行第二行代码。
发布于 2019-12-06 03:43:30
您正在使用的函数是异步的,因此第二个函数的响应可以在第一个函数的响应之前收到。
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");
appendFile(lines);
});
let appendFile = (lines)=> {
fs.appendFile('list.txt', '[' + lines + ']' + item + '\n', function(err) {
console.log("Im supposed to run second");
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);
});
});
}https://stackoverflow.com/questions/59202137
复制相似问题