fs.promises
时间: 2023-10-13 07:28:26 浏览: 70
`fs.promises` 是 Node.js 中的一个模块,它提供了一组 Promise 风格的文件系统 API,这些 API 对文件系统进行操作,如读取、写入、重命名、删除等。使用 Promise 风格的 API 可以简化异步代码的编写,避免回调地狱。
示例代码:
```javascript
const fs = require('fs').promises;
// 读取文件
fs.readFile('/path/to/file')
.then(data => console.log(data))
.catch(err => console.error(err));
// 写入文件
fs.writeFile('/path/to/file', 'hello world')
.then(() => console.log('write file success'))
.catch(err => console.error(err));
// 重命名文件
fs.rename('/path/to/file', '/path/to/newfile')
.then(() => console.log('rename file success'))
.catch(err => console.error(err));
// 删除文件
fs.unlink('/path/to/file')
.then(() => console.log('delete file success'))
.catch(err => console.error(err));
```
需要注意的是,`fs.promises` 在 Node.js 10 版本中引入,因此在使用之前需要确保 Node.js 的版本不低于 10。