Nodejs check file exists, if not, wait till it exist

前端 未结 7 718
一向
一向 2021-02-05 08:54

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:

f         


        
相关标签:
7条回答
  • 2021-02-05 09:26

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

    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)
      })
    }
    
    0 讨论(0)
提交回复
热议问题