Search code examples
node.jswritefile

Node.js how to cancel a WriteFile operation


Is there a way to cancel a WriteFile operation?

example:

     await promises.writeFile(path, data)

Solution

  • Yes you need to create an AbortController and pass it into your writeFile call:

    const fs = require('fs')
    
    // Some stub values
    const tempFilePath = () => `/tmp/foo`
    data = 'bar'
    
    
    const myAbortController = new AbortController()
    // With callback
    fs.writeFile(tempFilePath(), data, { signal: myAbortController.signal }, (err) => {
      if(err) {
        if(err.name === "AbortError") {
          console.warn("write aborted")
          return
        }
        throw err
      }
    })
    // Or with promises
    fs.promises.writeFile(tempFilePath(), data, { signal: myAbortController.signal })
      .catch((err) =>  {
        if(err.name === "AbortError") {
          console.warn("write aborted")
          return
        }
        throw err
      })
    // Or Async/Await
    ;(async () => {
      try {
        await fs.promises.writeFile(tempFilePath(), data, { signal: myAbortController.signal })
      } catch (err) {
        if(err.name === "AbortError") {
          console.warn("write aborted")
          return
        }
          throw err
      }
    })()
    
    // Somewhere else...
    myAbortController.abort()
    
    

    The code is tested and runs in v18, v16, and v14 with the --experimental-abortcontroller flag