Nodejs检查文件是否存在,如果不存在,则等待它存在

时间:2020-12-08 13:26:49

I'm generating files automatically, and I have another script which will check if a given file is already generated, so how could I implement such a function:

我正在自动生成文件,我有另一个脚本来检查是否已经生成了一个给定的文件,所以我怎么能实现这样一个函数:

function checkExistsWithTimeout(path, timeout)

which will check if a path exists, if not, wait for it, util timeout.

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

5 个解决方案

#1


1  

Here is the solution:

这是解决方案:

// 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);
};

#2


1  

Assuming you're planning on using Promises since you did not supply a callback in your method signature, you could check if the file exists and watch the directory at the same time, then resolve if the file exists, or the file is created before the timeout occurs.

假设您计划使用Promise,因为您没有在方法签名中提供回调,您可以检查文件是否存在并同时查看目录,然后解析文件是否存在,或者文件是否在超时发生。

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();
            }
        });
    });
}

#3


0  

This is very much a hack, but works for quick stuff.

这是一个非常黑客,但适用于快速的东西。

function wait (ms) {
    var now = Date.now();
    var later = now + ms;
    while (Date.now() < later) {
        // wait
    }
}

#4


0  

You could implement it like this if you have node 6 or higher.

如果您有节点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)
  })
}

#5


-1  

fs.watch() API is what you need.

fs.watch()API就是您所需要的。

Be sure to read all the caveats mentioned there before you use it.

在使用它之前,请务必阅读那里提到的所有警告。

#1


1  

Here is the solution:

这是解决方案:

// 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);
};

#2


1  

Assuming you're planning on using Promises since you did not supply a callback in your method signature, you could check if the file exists and watch the directory at the same time, then resolve if the file exists, or the file is created before the timeout occurs.

假设您计划使用Promise,因为您没有在方法签名中提供回调,您可以检查文件是否存在并同时查看目录,然后解析文件是否存在,或者文件是否在超时发生。

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();
            }
        });
    });
}

#3


0  

This is very much a hack, but works for quick stuff.

这是一个非常黑客,但适用于快速的东西。

function wait (ms) {
    var now = Date.now();
    var later = now + ms;
    while (Date.now() < later) {
        // wait
    }
}

#4


0  

You could implement it like this if you have node 6 or higher.

如果您有节点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)
  })
}

#5


-1  

fs.watch() API is what you need.

fs.watch()API就是您所需要的。

Be sure to read all the caveats mentioned there before you use it.

在使用它之前,请务必阅读那里提到的所有警告。