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 module "node:fs"fs = var require: NodeJS.Require
(id: string) => any
require('node:fs');
const const folderName: "/Users/joe/test"folderName = '/Users/joe/test';
try {
if (!module "node:fs"fs.function existsSync(path: fs.PathLike): booleanexistsSync(const folderName: "/Users/joe/test"folderName)) {
module "node:fs"fs.function mkdirSync(path: fs.PathLike, options?: fs.Mode | (fs.MakeDirectoryOptions & {
recursive?: false | undefined;
}) | null): void (+2 overloads)
mkdirSync(const folderName: "/Users/joe/test"folderName);
}
} catch (var err: unknownerr) {
var console: Consoleconsole.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)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 module "node:fs"fs = var require: NodeJS.Require
(id: string) => any
require('node:fs');
const const folderPath: "/Users/joe"folderPath = '/Users/joe';
module "node:fs"fs.function readdirSync(path: fs.PathLike, options?: {
encoding: BufferEncoding | null;
withFileTypes?: false | undefined;
recursive?: boolean | undefined;
} | BufferEncoding | null): string[] (+4 overloads)
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 module "node:fs"fs = var require: NodeJS.Require
(id: string) => any
require('node:fs');
const const isFile: (fileName: any) => booleanisFile = fileName: anyfileName => {
return module "node:fs"fs.const lstatSync: fs.StatSyncFn
(path: fs.PathLike, options?: undefined) => fs.Stats (+6 overloads)
lstatSync(fileName: anyfileName).StatsBase<number>.isFile(): booleanisFile();
};
module "node:fs"fs.function readdirSync(path: fs.PathLike, options?: {
encoding: BufferEncoding | null;
withFileTypes?: false | undefined;
recursive?: boolean | undefined;
} | BufferEncoding | null): string[] (+4 overloads)
readdirSync(folderPath)
.Array<string>.map<any>(callbackfn: (value: string, index: number, array: string[]) => any, thisArg?: any): any[]map(fileName: stringfileName => {
return path.join(folderPath, fileName: stringfileName);
})
.Array<any>.filter(predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): any[] (+1 overload)filter(const isFile: (fileName: any) => booleanisFile);
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 module "node:fs"fs = var require: NodeJS.Require
(id: string) => any
require('node:fs');
module "node:fs"fs.function rename(oldPath: fs.PathLike, newPath: fs.PathLike, callback: fs.NoParamCallback): voidrename('/Users/joe', '/Users/roger', err: NodeJS.ErrnoException | nullerr => {
if (err: NodeJS.ErrnoException | nullerr) {
var console: Consoleconsole.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)error(err: NodeJS.ErrnoExceptionerr);
}
// done
});
fs.renameSync() is the synchronous version:
const module "node:fs"fs = var require: NodeJS.Require
(id: string) => any
require('node:fs');
try {
module "node:fs"fs.function renameSync(oldPath: fs.PathLike, newPath: fs.PathLike): voidrenameSync('/Users/joe', '/Users/roger');
} catch (var err: unknownerr) {
var console: Consoleconsole.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)error(var err: unknownerr);
}
fsPromises.rename() is the promise-based version:
const module "node:fs/promises"fs = var require: NodeJS.Require
(id: string) => any
require('node:fs/promises');
async function function example(): Promise<void>example() {
try {
await module "node:fs/promises"fs.function rename(oldPath: PathLike, newPath: PathLike): Promise<void>rename('/Users/joe', '/Users/roger');
} catch (function (local var) err: unknownerr) {
var console: Consoleconsole.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)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 module "node:fs"fs = var require: NodeJS.Require
(id: string) => any
require('node:fs');
module "node:fs"fs.function rmdir(path: fs.PathLike, callback: fs.NoParamCallback): void (+1 overload)rmdir(dir, err: NodeJS.ErrnoException | nullerr => {
if (err: NodeJS.ErrnoException | nullerr) {
throw err: NodeJS.ErrnoExceptionerr;
}
var console: Consoleconsole.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)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 module "node:fs"fs = var require: NodeJS.Require
(id: string) => any
require('node:fs');
module "node:fs"fs.function rm(path: fs.PathLike, options: fs.RmOptions, callback: fs.NoParamCallback): void (+1 overload)rm(dir, { RmOptions.recursive?: boolean | undefinedrecursive: true, RmOptions.force?: boolean | undefinedforce: true }, err: NodeJS.ErrnoException | nullerr => {
if (err: NodeJS.ErrnoException | nullerr) {
throw err: NodeJS.ErrnoExceptionerr;
}
var console: Consoleconsole.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)log(`${dir} is deleted!`);
});