我自动生成文件,并且我有另一个脚本来检查给定的文件是否已经生成,所以我如何实现这样的功能:Nodejs检查文件存在,如果没有,等到它存在
function checkExistsWithTimeout(path, timeout)
这将检查路径是否存在,如果没有,等待它,util超时。
我自动生成文件,并且我有另一个脚本来检查给定的文件是否已经生成,所以我如何实现这样的功能:Nodejs检查文件存在,如果没有,等到它存在
function checkExistsWithTimeout(path, timeout)
这将检查路径是否存在,如果没有,等待它,util超时。
fs.watch() API是你所需要的。
请务必在使用前阅读所有提及的注意事项。
我不觉得这是如此有用fs.watch似乎需要该文件存在才可以观看... – 2017-09-06 16:44:36
这是非常黑客,但适用于快速的东西。
function wait (ms) {
var now = Date.now();
var later = now + ms;
while (Date.now() < later) {
// wait
}
}
这里是解决方案:
// Wait for file to exist, checks every 2 seconds
function getFile(path, timeout) {
const timeout = setInterval(function() {
const file = path;
const fileExists = fs.existsSync(file);
console.log('Checking for: ', file);
console.log('Exists: ', fileExists);
if (fileExists) {
clearInterval(timeout);
}
}, timeout);
};
您可以实现像这样,如果你有节点6或更高。
const fs = require('fs')
function checkExistsWithTimeout(path, timeout) {
return new Promise((resolve, reject) => {
const timeoutTimerId = setTimeout(handleTimeout, timeout)
const interval = timeout/6
let intervalTimerId
function handleTimeout() {
clearTimeout(timerId)
const error = new Error('path check timed out')
error.name = 'PATH_CHECK_TIMED_OUT'
reject(error)
}
function handleInterval() {
fs.access(path, (err) => {
if(err) {
intervalTimerId = setTimeout(handleInterval, interval)
} else {
clearTimeout(timeoutTimerId)
resolve(path)
}
})
}
intervalTimerId = setTimeout(handleInterval, interval)
})
}
假设你计划使用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();
}
});
});
}
你定位的操作系统是什么?在Linux/OSX上,您可以让Node.js监视目录以进行更改。 – Brad 2014-10-02 17:00:15
我在Linux上运行代码 – wong2 2014-10-02 17:07:34
这可能会有用; http://nodejs.org/docs/latest/api/fs.html#fs_fs_watchfile_filename_options_listener – renatoargh 2014-10-02 18:14:37