[英]How can i set a timeout to this function in node js?
我从 async 模块中有这个函数,它从输入文件数组中读取,例如:
inputs: ['file1.txt', 'file2.txt']
map(inputs, fs.readFile,
(err, contents) => {
if (err) console.log('Error: ' + err);
else {
const data = contents.reduce((a, b) => a + b);
fs.writeFile(output, data, () => console.log(`Output in file '${output}'`)
);
}
}
);
如何为 fs.readFile 调用设置超时? 例如,我希望在 3 秒后执行此操作。 例如,我正在尝试这个,但它不起作用,我猜它是一个语法问题,我没有像它应该的那样编写它:
map(inputs, setTimeout(fs.readFile,3000),
(err, contents) => {
if (err) console.log('Error: ' + err);
else {
const data = contents.reduce((a, b) => a + b);
fs.writeFile(output, data, () => console.log(`Output in file '${output}'`)
);
}
}
);
这应该很容易,但我卡住了。 也许我不能把超时放在地图函数中? 我应该创建一个新函数,而不是调用 fs.readFile,而是调用我的函数? 先感谢您。
即使您要为这些文件找到正确的时间,它也会在文件内容发生更改时中断,并且添加超时的想法是 node.js 中的完全反模式。
如果文件不是很大,您可以阅读所有文件并在之后连接它们:
const { promisify } = require('util');
const fs = require('fs');
// Create Promise versions of the fs calls we will need
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
/**
* @param {string[]} files - Paths to the files to concatene
* @param {string} destination - Path of the concatenated file
*/
async function concat(files, destination) {
// Read all files, Promise.all allow to have all operation happening in parallel
const contents = await Promise.all(files.map(readFile));
// content.join('') may not work as you want, replace it with whatever concatenation you need
return writeFile(destination, contents.join(''));
}
如果您不能一次保存多个文件,您可以一个接一个地附加它们。
const fs = require('fs');
const { promisify } = require('util');
const readFile = promisify(fs.readFile);
const appendFile = promisify(fs.appendFile);
/**
* @param {string[]} files - Paths to the files to concatene
* @param {string} destination - Path of the concatenated file
*/
async function concat(files, destination) {
// For each file
for(const file of files) {
// Read it
const content = await readFile(file);
// Append at the end of concatenated file
await appendFile(destination, content);
}
}
没有测试代码,可能到处都是语法错误,但你应该明白了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.