gpt4 book ai didi

node.js - nodejs检查文件是否存在,如果不存在,等到存在

转载 作者:IT老高 更新时间:2023-10-28 23:08:32 26 4
gpt4 key购买 nike

我正在自动生成文件,并且我有另一个脚本将检查给定文件是否已经生成,那么我该如何实现这样的功能:

function checkExistsWithTimeout(path, timeout)

它将检查路径是否存在,如果不存在,则等待它,util timeout。

最佳答案

假设您计划使用 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();
}
});
});
}

关于node.js - nodejs检查文件是否存在,如果不存在,等到存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26165725/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com