我正在自动生成文件,我有另一个脚本来检查是否已经生成了给定文件,所以我该如何实现这样的功能:
function checkExistsWithTimeout(path, timeout)
Run Code Online (Sandbox Code Playgroud)
这将检查路径是否存在,如果不存在,则等待它,util超时.
Jak*_*ger 10
假设您计划使用,Promises因为您没有在方法签名中提供回调,您可以检查文件是否存在并同时查看目录,然后解析文件是否存在,或者文件是否在超时之前创建发生.
function checkExistsWithTimeout(filePath, timeout) {
return new Promise(function (resolve, reject) {
var timer = setTimeout(function () {
watcher.close();
reject(new Error('File did not exists and was not created during the timeout.'));
}, timeout);
fs.access(filePath, fs.constants.R_OK, function (err) {
if (!err) {
clearTimeout(timer);
watcher.close();
resolve();
}
});
var dir = path.dirname(filePath);
var basename = path.basename(filePath);
var watcher = fs.watch(dir, function (eventType, filename) {
if (eventType === 'rename' && filename === basename) {
clearTimeout(timer);
watcher.close();
resolve();
}
});
});
}
Run Code Online (Sandbox Code Playgroud)
fs.watch() API 正是您所需要的。
在使用之前,请务必阅读其中提到的所有注意事项。
| 归档时间: |
|
| 查看次数: |
12748 次 |
| 最近记录: |