Working with folders in Node.js

The Node.js fs core module provides many handy methods you can use to work with folders.

Check if a folder exists

Use fs.access() (and its promise-based fsPromises.access() counterpart) to check if the folder exists and Node.js can access it with its permissions.

Create a new folder

Use fs.mkdir() or fs.mkdirSync() or fsPromises.mkdir() to create a new folder.

const import fsfs = require: anyrequire('node:fs');

const const folderName: "/Users/joe/test"folderName = '/Users/joe/test';

try {
  if (!import fsfs.existsSync(const folderName: "/Users/joe/test"folderName)) {
    import fsfs.mkdirSync(const folderName: "/Users/joe/test"folderName);
  }
} catch (var err: unknownerr) {
  var console: Consoleconsole.Console.error(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static)
error
(var err: unknownerr);
}

Read the content of a directory

Use fs.readdir() or fs.readdirSync() or fsPromises.readdir() to read the contents of a directory.

This piece of code reads the content of a folder, both files and subfolders, and returns their relative path:

const import fsfs = require: anyrequire('node:fs');

const const folderPath: "/Users/joe"folderPath = '/Users/joe';

import fsfs.readdirSync(const folderPath: "/Users/joe"folderPath);

You can get the full path:

fs.readdirSync(folderPath).map(fileName: anyfileName => {
  return path.join(folderPath, fileName: anyfileName);
});

You can also filter the results to only return the files, and exclude the folders:

const import fsfs = require: anyrequire('node:fs');

const const isFile: (fileName: any) => anyisFile = fileName: anyfileName => {
  return import fsfs.lstatSync(fileName: anyfileName).isFile();
};

import fsfs.readdirSync(folderPath)
  .map(fileName: anyfileName => {
    return path.join(folderPath, fileName: anyfileName);
  })
  .filter(const isFile: (fileName: any) => anyisFile);

Rename a folder

Use fs.rename() or fs.renameSync() or fsPromises.rename() to rename folder. The first parameter is the current path, the second the new path:

const import fsfs = require: anyrequire('node:fs');

import fsfs.rename('/Users/joe', '/Users/roger', err: anyerr => {
  if (err: anyerr) {
    var console: Consoleconsole.Console.error(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static)
error
(err: anyerr);
} // done });

fs.renameSync() is the synchronous version:

const import fsfs = require: anyrequire('node:fs');

try {
  import fsfs.renameSync('/Users/joe', '/Users/roger');
} catch (var err: unknownerr) {
  var console: Consoleconsole.Console.error(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static)
error
(var err: unknownerr);
}

fsPromises.rename() is the promise-based version:

const import fsfs = require: anyrequire('node:fs/promises');

async function function example(): Promise<void>example() {
  try {
    await import fsfs.rename('/Users/joe', '/Users/roger');
  } catch (function (local var) err: unknownerr) {
    var console: Consoleconsole.Console.log(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(function (local var) err: unknownerr);
} } function example(): Promise<void>example();

Remove a folder

Use fs.rmdir() or fs.rmdirSync() or fsPromises.rmdir() to remove a folder.

const import fsfs = require: anyrequire('node:fs');

import fsfs.rmdir(dir, err: anyerr => {
  if (err: anyerr) {
    throw err: anyerr;
  }

  var console: Consoleconsole.Console.log(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(`${dir} is deleted!`);
});

To remove a folder that has contents use fs.rm() with the option { recursive: true } to recursively remove the contents.

{ recursive: true, force: true } makes it so that exceptions will be ignored if the folder does not exist.

const import fsfs = require: anyrequire('node:fs');

import fsfs.rm(dir, { recursive: booleanrecursive: true, force: booleanforce: true }, err: anyerr => {
  if (err: anyerr) {
    throw err: anyerr;
  }

  var console: Consoleconsole.Console.log(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(`${dir} is deleted!`);
});