fs-extended

Extends native fs module with a lot of convenient methods.

fs-extended

Node.js module that extends the native fs with a lot of convenient methods.

If you miss a method, and there is more than 1 person in the world that would use it, create an issue!.

None.

Changelog

Upholds the Semantic Versioning Specification.

npm install fs-extended
var fs = require('fs-extended');
 
fs.listFiles('foo', { recursive: 1 }, function (errfiles) {
    console.log(err, files);
});

All methods from native fs module are available.

Creates a new, or overrides an existing file. Creates any missing parent directories.

  • path String Path to a file.
  • data String|Buffer Contents of a new file.
  • [options] Object Object with options (will be passed to fs.writeFile):
    • encoding String|Null File encoding. Defaults to utf8.
    • mode Number File mode. Defaults to 0666. The final mode is dependent on process umask.
    • flag String File open flag. Defaults to w.
  • [callback] Function Receives arguments:
    • err Mixed Error object on error, null otherwise.

Synchronous fs.createFile();

Ensures file exists. If it does, it'll only ensure file mode (when passed). If it doesn't, it'll create an empty file. Creates any missing parent directories.

  • path String Path to a file.
  • [mode] Object File mode. Defaults to 0666. The final mode is dependent on process umask.
  • [callback] Function Receives arguments:
    • err Mixed Error object on error, null otherwise.

Synchronous fs.ensureFile();

Copies a file from one location to another. Creates any missing destination directories, and works between different partitions/filesystems. Also makes sure that file mode is preserved.

  • oldPath String Path to original file.
  • newPath String Destination path.
  • [callback] Function Receives arguments:
    • err Mixed Error object on error, null otherwise.

Synchronous fs.copyFile();

Moves a file from one location to another. Creates any missing destination directories, and works between different partitions/filesystems. Also makes sure that file mode is preserved.

  • oldPath String Path to original file.
  • newPath String Destination path.
  • [callback] Function Receives arguments:
    • err Mixed Error object on error, null otherwise.

Synchronous fs.moveFile();

Deletes all contents of a file. When file doesn't exist, it is created with a default mode 0666.

A mere alias of fs.truncate(file, 0, callback) with an optional callback for API consistency.

  • file String Path to a file.
  • [callback] Function Receives arguments:
    • err Mixed Error object on error, null otherwise.

Synchronous fs.emptyFile();

Deletes a file. Doesn't throw an error when file doesn't exist.

A mere alias of fs.unlink(file, callback) with ignored ENOENT error and an optional callback for API consistency.

  • file String Path to a file.
  • [callback] Function Receives arguments:
    • err Mixed Error object on error, null otherwise.

Synchronous fs.deleteFile();


Creates a directory, and any missing parent directories. If directory exists, it only ensures mode (when passed).

  • dir String Path to a new directory.
  • [mode] Object Directory mode. Defaults to 0777. The final mode is dependent on process umask.
  • [callback] Function Receives arguments:
    • err Mixed Error object on error, null otherwise.

Synchronous fs.createDir();

Alias of fs.createDir() for API consistency.

Alias of fs.createDirSync() for API consistency.

Copies a directory and everything in it from one location to another. Creates any missing destination directories, and works between different partitions/filesystems. Also makes sure that mode of all items is preserved.

  • oldPath String Path to original directory.
  • newPath String Destination path.
  • [callback] Function Receives arguments:
    • err Mixed Error object on error, null otherwise.

Synchronous fs.copyDir();

Moves a directory and everything in it from one location to another. Creates any missing destination directories, and works between different partitions/filesystems. Also makes sure that mode of all items is preserved.

  • oldPath String Path to original directory.
  • newPath String Destination path.
  • [callback] Function Receives arguments:
    • err Mixed Error object on error, null otherwise.

Synchronous fs.moveDir();

Deletes everything inside a directory, but keeps the directory itself.

  • dir String Path to directory.
  • [callback] Function Receives arguments:
    • err Mixed Error object on error, null otherwise.

Synchronous fs.emptyDir();

Deletes a directory and everything inside it.

  • dir String Path to directory.
  • [callback] Function Receives arguments:
    • err Mixed Error object on error, null otherwise.

Synchronous fs.deleteDir();


Copy based on a type of the original item. Bridges to fs.copyFile() when oldPath is a file, or fs.copyDir() when it's a directory.

  • oldPath String Path to a file or a directory.
  • newPath String Destination path.
  • [callback] Function Receives arguments:
    • err Mixed Error object on error, null otherwise.

Synchronous fs.copy();

Move based on a type of the original item. Bridges to fs.moveFile() when oldPath is a file, or fs.moveDir() when it's a directory.

  • oldPath String Path to a file or a directory.
  • newPath String Destination path.
  • [callback] Function Receives arguments:
    • err Mixed Error object on error, null otherwise.

Synchronous fs.move();

Empty based on a type of the original item. Bridges to fs.emptyFile() when target is a file, or fs.emptyDir() when it's a directory.

  • target String Path to a file or a directory.
  • [callback] Function Receives arguments:
    • err Mixed Error object on error, null otherwise.

Synchronous fs.empty();

Delete based on a type of the original item. Bridges to fs.deleteFile() when target is a file, or fs.deleteDir() when it's a directory.

  • target String Path to a file or a directory.
  • [callback] Function Receives arguments:
    • err Mixed Error object on error, null otherwise.

Synchronous fs.delete();


List all directories and files inside a directory.

  • dir String Path to a directory.
  • [options] Object Object with options:
    • recursive Boolean List items recursively, expanding all child directories. Defaults to false.
    • prependDir Boolean Prepend dir path before every item in final array. Defaults to false.
    • filter Function Function to filter items. Should return true or false. Receives arguments:
      • itemPath String Full path to an item.
      • stat fs.Stats Object with data about a file.
    • map Function Function to map final list items. Mapping is applied after filter. Receives arguments:
      • itemPath String Full path to an item.
      • stat fs.Stats Object with data about a file.
    • sort Boolean | Function Pass true to sort files lexicographically, or a compare function you'd normally pass to an Array.sort(). Sorting is applied after filter & map. Function accepts two file paths (or whatever map returned) for comparison.
  • [callback] Function Receives arguments:
    • err Mixed Error object on error, null otherwise.
    • list Array List of items inside a directory.

The purpose of built-in filter/map functions is to recycle fs.Stats objects when needed, as loading this objects is the biggest bottleneck when listing files recursively.

The fs.Stats for each file is loaded only when recursive listing is requested, or filter/map functions accept it as an argument.

On the other hand, if your filter/map needs something that fs.Stat provides, just use it. There is no way how to make data retrieval by fs.stat() faster (I'd like to be corrected on this if I'm wrong! :)).

Filter out directories, effectively turning fs.listAll() into fs.listFiles():

function filter(itemPathstat) {
    return stat.isFile();
}
 
fs.listAll(dir, { filter: filter }, function (errfiles) {
    console.log(err);   // possible exception 
    console.log(files); // array of all files inside a directory 
});

Map files into a more descriptive array of objects:

function map(itemPathstat) {
    return {
        path: itemPath,
        name: path.basename(itemPath),
        ext: path.extname(itemPath),
        size: stat.size,
    };
}
 
fs.listAll(dir, { map: map }, function (errfiles) {
    console.log(err);   // possible exception 
    console.log(files); // array of file object descriptors returned by map() 
    // Example 
    files[0].path; // 1st file's path 
    files[0].ext;  // 1st file's extension 
});

Sort files by their name lexicographically:

fs.listAll(dir, { sort: true }, function (errfiles) {
    console.log(err);   // possible exception 
    console.log(files); // sorted array of files 
});

Sort files by their extension with a compare function:

function compare(ab) {
    return path.extname(a) < path.extname(b) ? -1 : 1;
}
 
fs.listAll(dir, { sort: compare }, function (errfiles) {
    console.log(err);   // possible exception 
    console.log(files); // sorted array of files 
});

Synchronous fs.listAll();

List all files inside a directory.

  • dir String Path to a directory.
  • [options] Object Object with options:
    • recursive Boolean List files recursively, expanding all child directories. Defaults to false.
    • prependDir Boolean Prepend dir path before every item in final array. Defaults to false.
    • filter Function Function to filter items. Should return true or false. Receives arguments:
      • filePath String Full path to a file.
      • stat fs.Stats Object with data about a file.
    • map Function Function to map final list items. Mapping is applied after filter. Receives arguments:
      • filePath String Full path to a file.
      • stat fs.Stats Object with data about a file.
    • sort Boolean | Function Pass true to sort files lexicographically, or a compare function you'd normally pass to an Array.sort(). Sorting is applied after filter & map. Function accepts two file paths (or whatever map returned) for comparison.
  • callback Function Receives arguments:
    • err Mixed Error object on error, null otherwise.
    • files Array List of files inside a directory.

List all files in a directory recursively, and sort them by size:

function map(filePathstat) {
    return {
        path: filePath,
        size: stat.size,
    };
}
 
function compare(ab) {
    return a.size < b.size ? -1 : 1;
}
 
fs.listAll(dir, { map: map, sort: compare }, function (errfiles) {
    console.log(err);   // possible exception 
    console.log(files); // array of file object descriptors returned by map() 
    // Example 
    files[0].path; // 1st file's path 
    files[0].size; // 1st file's size 
});

Synchronous fs.listFiles();

List all directories inside a directory.

  • dir String Path to a directory.
  • [options] Object Object with options:
    • recursive Boolean List directories recursively, expanding all child directories. Defaults to false.
    • prependDir Boolean Prepend dir path before every directory in final array. Defaults to false.
    • filter Function Function to filter items. Function should return true or false. Receives arguments:
      • dirPath String Full path to a directory.
      • stat fs.Stats Object with data about a directory.
    • map Function Function to map final list items. Mapping is applied after filter. Receives arguments:
      • dirPath String Full path to a directory.
      • stat fs.Stats Object with data about a directory.
    • sort Boolean | Function Pass true to sort directories lexicographically, or a compare function you'd normally pass to an Array.sort(). Sorting is applied after filter & map. Function accepts two directory paths (or whatever map returned) for comparison.
  • callback Function Receives arguments:
    • err Mixed Error object on error, null otherwise.
    • dirs Array List of directories inside a directory.

List all directories in a directory recursively, and sort them by modification time:

function map(dirPathstat) {
    return {
        path: dirPath,
        mtime: stat.mtime,
    };
}
 
function compare(ab) {
    return a.mtime < b.mtime ? -1 : 1;
}
 
fs.listAll(dir, { map: map, sort: compare }, function (errfiles) {
    console.log(err);   // possible exception 
    console.log(files); // array of file object descriptors returned by map() 
    // Example 
    files[0].path;  // 1st directory's path 
    files[0].mtime; // 1st directory's mtime 
});

Synchronous fs.listDirs();


Generates a unique path that won't override any other file.

If path doesn't exist, it is simply returned. Otherwise it will insert "-N" suffix between the file name and its extension (if there is any) until it finds a path that doesn't exist yet.

Be aware of Race condition!

  • path String Path to be uniquefied.
  • [no] Integer Starting number index. Defaults to 2.
  • callback Function Receives arguments:
    • uniquePath String Unique version of the original path.

With a directory structure:

dir
├─ foo
├─ bar.txt
├─ bar-2.txt
├─ bar-3.txt
└─ baz.tar.gz

These are the outputs:

fs.uniquePath('dir/unique', function (uniquePath) {
    uniquePath; // => dir/unique 
});
fs.uniquePath('dir/foo', function (uniquePath) {
    uniquePath; // => dir/foo-2 
});
fs.uniquePath('dir/bar.txt', function (uniquePath) {
    uniquePath; // => dir/bar-4.txt 
});
fs.uniquePath('dir/baz.tar.gz', function (uniquePath) {
    uniquePath; // => dir/baz-2.tar.gz 
});

Synchronous fs.uniquePath();

Format data in JSON and write into a file. Creates destination directory if it doesn't exist yet.

  • file String Path to a destination file.
  • data Mixed Data to be formated in JSON.
  • [indentation] Mixed Number of spaces, or a direct representation of a single indentation level, like '\t'. Defaults to no indentation.
  • [callback] Function Receives arguments:
    • err Mixed Error object on error, null otherwise.

Alias: fs.writeJson()

Synchronous fs.writeJSON();

Alias: fs.writeJsonSync()

Encode data in JSON format and write into a file. Creates destination directory if it doesn't exist yet.

  • file String Path to a JSON file.
  • callback Function Receives arguments:
    • err Mixed Error object on error, null otherwise.
    • data Mixed Data from JSON file.

Alias: fs.readJson()

Synchronous fs.readJSON();

Alias: fs.readJsonSync()