function readFile(){
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream(FILE_PATH)
});
lineReader.on('line', function (line) {
setTimeout(() => {
console.log("HEYYYYY");
}, 10000);
});
}
Why does this only waits 10 seconds once , and the prints 'hey' ? I want to print hey each 10 seconds but it's not working. No idea why.
Edit: This is going to be repeated by the amount of lines that there are on a file (look at the listener 'line') I need to delay 10s between each line.
I had the same problem and I solved it with the "Example: Read File Stream Line-by-Line" found in: https://nodejs.org/api/readline.html
In your case it would be something like this:
const fs = require('fs');
const readline = require('readline');
async function processLineByLine() {
const fileStream = fs.createReadStream(FILE_PATH);
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in input.txt as a single line break.
for await (const line of rl) {
// Each line in input.txt will be successively available here as `line`.
console.log(`Line from file: ${line}`);
await sleep(10000)
}
}
function sleep(ms){
return new Promise(resolve=>{
setTimeout(resolve,ms)
})
}
This example would print you a line every 10 seconds.
It's not waiting 10 seconds once. its just that each line is read so fast, there's almost not difference in the start time. you can add a variable that increase the delay by 10 seconds in each callback so you each line is print each 10 seconds.
function readFile(){
var delay = 0;
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream(FILE_PATH)
});
lineReader.on('line', function (line) {
delay += 10000;
setTimeout(() => {
console.log("HEYYYYY");
}, 10000+delay);
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.