const express = require('express');
const fs = require('fs');
const readLine = require('readline')
const app = express();
const port = 3000;
app.get('/', (req, res, next) => {
let aylinResponseArray = [];
let sendLine = readLine.createInterface({
input: fs.createReadStream('my-file.txt'),
});
sendLine.on('line', (line) => {
//multiple async API calls made here, I push response on my API's done callback.
}).on('close', function() {
console.log('finished');
});
res.end();
});
当我进入端点并运行它时,我先完成了一切。显然,我没有正确使用异步/等待原则,很高兴收到您的经验。
我尝试了不同的方法,发现了一种与我要寻找的方法接近的方法:
const { once } = require('events');
const { createReadStream } = require('fs');
const { createInterface } = require('readline');
(async function processLineByLine() {
try {
const rl = createInterface({
input: createReadStream('big-file.txt'),
crlfDelay: Infinity
});
rl.on('line', (line) => {
// Process the line.
});
await once(rl, 'close');
console.log('File processed.');
} catch (err) {
console.error(err);
}
})();
但是我收到来自节点的转码错误,指出该once is not a function
。
我只是将以上内容作为试用版提供,如果您对以上代码有更简单的解决方案,请告诉我