Nodejs检查文件是否存在,如果没有,等到它存在
我自动生成文件,我有另一个脚本,将检查给定的文件是否已经生成,所以我怎么能实现这样的function:
function checkExistsWithTimeout(path, timeout)
这将检查path是否存在,如果没有,等待它,util超时。
fs.watch() API是你所需要的。
在使用之前,请务必阅读所有提到的注意事项。
这是一个非常黑客,但快速的东西的作品。
function wait (ms) { var now = Date.now(); var later = now + ms; while (Date.now() < later) { // wait } }
这是解决scheme:
// 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
因为你没有在你的方法签名中提供callback函数,你可以检查文件是否存在并同时观察目录,然后parsing文件是否存在,或者文件是否在超时发生。
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(); } }); }); }