我可以在 Node.js 中逐行传输文件,如下所示:
var rd = readline.createInterface({
input: fs.createReadStream('/path/to/file'),
output: process.stdout,
terminal: false
});
rd.on('line', function(line) {
console.log(line);
});
有没有办法在每个 console.log()
调用之间添加间隔,同时使整个过程异步?
这意味着从程序的任何其他部分生成的任何日志语句都会与来自读取行的语句混合在控制台上发布
我的服务器正在监听需要发布的传入消息。当它们进来时,直到 readline
读取整个文件之后它们才会被发布。
最佳答案
每条消息仅以 1 秒的间隔处理
// debounce function - await fn call with timeout
// credits: https://remysharp.com/2010/07/21/throttling-function-calls
function debounce(fn, delay) {
var timer = null;
return function() {
var context = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(function() {
fn.apply(context, args);
}, delay);
};
}
rd.on('line', debounce(function(line) {
console.log(line);
}, 1000)); // <== call fn only within 1sec
伪输出:
1sec:
line: some text
log: some text
2sec:
line: another text
log: another text
2.5sec:
line: quick message text
2.9sec:
line: dota 2 manila major
3sec:
log: quick message text
log: dota 2 manila major
关于javascript - 如何在 Node.js 中使用 readline 模块时添加异步行读取之间的间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37709832/