Skip to content

Node.js fs API

Node.js fs module for filesystem access including reading, writing, listing and inspecting paths.

1 class · 5 methods

fs

5 methods

Promise-based and synchronous filesystem operations.

fs.readFile(path, options?) -> Promise<Buffer | string>

Asynchronously reads the entire contents of a file. Set encoding to receive a string.

Parameters

NameTypeDescription
pathstring | Buffer | URLFile path or file descriptor.
optionsobject | string{ encoding, flag } or encoding string.

Returns

Promise<Buffer | string>

Example

nodejs
import { readFile } from 'fs/promises';
const text = await readFile('./config.json', 'utf8');
fs.writeFile(path, data, options?) -> Promise<void>

Asynchronously writes data to a file, replacing the file if it already exists.

Parameters

NameTypeDescription
pathstring | Buffer | URLFile path or file descriptor.
datastring | Buffer | TypedArrayData to write.
optionsobject | string{ encoding, mode, flag }.

Returns

Promise<void>

Example

nodejs
import { writeFile } from 'fs/promises';
await writeFile('./log.txt', 'hello\n', { flag: 'a' });
fs.readdir(path, options?) -> Promise<string[] | Dirent[]>

Asynchronously reads the contents of a directory, returning names or Dirent objects with withFileTypes.

Parameters

NameTypeDescription
pathstring | Buffer | URLDirectory path.
optionsobject{ encoding, withFileTypes, recursive }.

Returns

Promise<string[] | Dirent[]>

Example

nodejs
import { readdir } from 'fs/promises';
const entries = await readdir('./src', { withFileTypes: true });
for (const e of entries) console.log(e.isDirectory() ? 'd' : 'f', e.name);
fs.stat(path, options?) -> Promise<Stats>

Asynchronously resolves file metadata such as size, mtime and type.

Parameters

NameTypeDescription
pathstring | Buffer | URLPath to inspect.

Returns

Promise<Stats>

Example

nodejs
import { stat } from 'fs/promises';
const s = await stat('./package.json');
console.log(s.size, s.mtime);
fs.mkdir(path, options?) -> Promise<string | undefined>

Asynchronously creates a directory; recursive: true creates parent directories as needed.

Parameters

NameTypeDescription
pathstring | Buffer | URLDirectory path to create.
optionsobject{ recursive, mode }.

Returns

Promise<string | undefined>

Example

nodejs
import { mkdir } from 'fs/promises';
await mkdir('./data/cache', { recursive: true });