fs
5 methodsPromise-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
| Name | Type | Description |
|---|---|---|
| path | string | Buffer | URL | File path or file descriptor. |
| options | object | 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
| Name | Type | Description |
|---|---|---|
| path | string | Buffer | URL | File path or file descriptor. |
| data | string | Buffer | TypedArray | Data to write. |
| options | object | 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
| Name | Type | Description |
|---|---|---|
| path | string | Buffer | URL | Directory path. |
| options | object | { 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
| Name | Type | Description |
|---|---|---|
| path | string | Buffer | URL | Path 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
| Name | Type | Description |
|---|---|---|
| path | string | Buffer | URL | Directory path to create. |
| options | object | { recursive, mode }. |
Returns
Promise<string | undefined>
Example
nodejs
import { mkdir } from 'fs/promises';
await mkdir('./data/cache', { recursive: true });