fs-extra

repository·master·Indexed 27 days ago

https://github.com/jprichardson/node-fs-extra

A drop-in replacement for the Node.js native fs module that adds extra file system methods such as copy, remove, ensureDir, and emptyDir, while providing built-in Promise support. Version 11.4.0.

Tokens
13.7K
Snippets
38
Records
71
Agent score
92%

What's inside fs-extra

  1. Use fs-extra with CommonJS

    master

    In CommonJS environments, fs-extra is a drop-in replacement for the native fs module. All native fs methods are attached to fs-extra, and all fs methods return promises if a callback is not provided.

    Note: The deprecated constants fs.F_OK, fs.R_OK, fs.W_OK, and fs.X_OK are not exported on Node.js v24.0.0+. Please use their fs.constants equivalents instead.

    const fse = require('fs-extra')
  2. Use fs-extra with ESM

    master

    For ESM, you can use fs-extra/esm which supports both default and named exports.

    Important: When using fs-extra/esm, native fs methods are not included. You must import fs or fs/promises separately if you need them. For a more seamless experience with both native and fs-extra methods, use the standard fs-extra import instead.

    // Using fs-extra/esm (requires separate fs imports for native methods)
    import { readFileSync } from 'fs'
    import { readFile } from 'fs/promises'
    import { outputFile, outputFileSync } from 'fs-extra/esm'
    
    // Recommended for ESM: use regular fs-extra for both native and extra methods
    import fs from 'fs-extra'
  3. Handle Async, Sync, and Async/Await patterns

    master

    Most fs-extra methods are asynchronous by default.

    • Async (Promises): Returns a promise if no callback is passed.
    • Async (Callbacks): Accepts a callback function.
    • Sync: Synchronous methods (suffixed with Sync) will throw an error if one occurs.
    • Async/Await: Standard await usage will throw an error if the operation fails.
    const fs = require('fs-extra')
    
    // Async with promises:
    fs.copy('/tmp/myfile', '/tmp/mynewfile')
      .then(() => console.log('success!'))
      .catch(err => console.error(err))
    
    // Async with callbacks:
    fs.copy('/tmp/myfile', '/tmp/mynewfile', err => {
      if (err) return console.error(err)
      console.log('success!')
    })
    
    // Sync:
    try {
      fs.copySync('/tmp/myfile', '/tmp/mynewfile')
      console.log('success!')
    } catch (err) {
      console.error(err)
    }
    
    // Async/Await:
    async function copyFiles () {
      try {
        await fs.copy('/tmp/myfile', '/tmp/mynewfile')
        console.log('success!')
      } catch (err) {
        console.error(err)
      }
    }
    
    copyFiles()
  4. Use fs-extra as a drop-in replacement for native fs

    master
    The fs-extra module exports all standard Node.js fs methods (via graceful-fs) and makes them universally accessible as both callback-based and Promise-based functions. Most standard fs methods are automatically converted to support Promises if a callback is not provided.
  5. Filter files during copySync()

    master

    You can provide a filter function in the options object of copySync() to selectively copy files or directories. The filter function is called for each item, and you must return true to include the item in the copy operation or false to skip it.

    const fs = require('fs-extra')
    
    const filterFunc = (src, dest) => {
      // your logic here
      // it will be copied if return true
    }
    
    fs.copySync('/tmp/mydir', '/tmp/mynewdir', { filter: filterFunc })
  6. Overwrite existing files or directories during move

    master

    To move a file or directory and overwrite the destination if it already exists, pass { overwrite: true } in the options argument of the move() method.

    const fs = require('fs-extra')
    
    fs.move('/tmp/somedir', '/tmp/may/already/exist/somedir', { overwrite: true }, err => {
      if (err) return console.error(err)
      console.log('success!')
    })
  7. Filter files during copy using the filter option

    master

    You can provide a filter function in the options object of copy() to selectively include or exclude files and directories. The function receives (src, dest) as arguments. Return true to include the item in the copy operation, or false to skip it. The filter function can be synchronous or return a Promise (async).

    const fs = require('fs-extra')
    
    const filterFunc = (src, dest) => {
      // your logic here
      // it will be copied if return true
    }
    
    fs.copy('/tmp/mydir', '/tmp/mynewdir', { filter: filterFunc }, err => {
      if (err) return console.error(err)
      console.log('success!')
    })
  8. Use `fs.write()` with Promises or async/await

    master

    When using fs.write() with fs-extra's promisified version, the returned Promise resolves to an object containing the number of bytes written and the buffer. This differs from the standard Node.js callback behavior where the callback receives 3 arguments.

    Resolved object shape:

    • bytesWritten: Number of bytes written.
    • buffer: The buffer containing the data.
    // With Promises:
    fs.write(fd, buffer, offset, length, position)
      .then(results => {
        console.log(results)
        // { bytesWritten: 20, buffer: <Buffer 0f 34 5d ...> }
      })
    
    // With async/await:
    async function example () {
      const { bytesWritten, buffer } = await fs.write(fd, Buffer.alloc(length), offset, length, position)
    }
  9. Use emptyDirSync(dir) to ensure a directory is empty

    master

    The emptyDirSync(dir) method ensures that a directory is empty. If the directory contains files or subdirectories, they are deleted. If the directory does not exist, it is created. Note that the directory itself is not deleted, only its contents.

    const fs = require('fs-extra')
    
    // assume this directory has a lot of files and folders
    fs.emptyDirSync('/tmp/some/dir')