http
5 methods来自 http 模块的服务器和客户端工具。
fs.readFile(path, options?) -> Promise<Buffer | string>返回新的 HTTP 服务器,为每个请求调用监听器。
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>发起 HTTP 请求并返回 ClientRequest;emit 'response' 或传递回调。
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[]>在给定端口和可选主机名上开始监听连接。
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>GET 请求的便捷方法;自动调用 req.end()。
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 });