Skip to content

Node.js fs API

Node.js http 模块,用于构建 HTTP 服务器和发起 HTTP 客户端请求。

1 class · 5 methods

http

5 methods

来自 http 模块的服务器和客户端工具。

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

返回新的 HTTP 服务器,为每个请求调用监听器。

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>

发起 HTTP 请求并返回 ClientRequest;emit 'response' 或传递回调。

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[]>

在给定端口和可选主机名上开始监听连接。

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>

GET 请求的便捷方法;自动调用 req.end()。

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 });