javascript - fs.unlink 异步 node.js
问题描述
删除 async 并 await 代码正常工作时,如果 unlink 是 async 函数,出现此错误有什么问题?在这种情况下,由于取消链接仅删除文件函数并返回 null,因此在 Promise 中是否必须有一个 resolve(...) ?
c:\Users\Flavio\Documents\Coding\projects-my\study-content\study-luiz-miranda\node\file-system\unlink.js:7
let deletedFile = await fs.unlink(path.join(dir, file));
^^^^^
SyntaxError: await is only valid in async function
at wrapSafe (internal/modules/cjs/loader.js:984:16)
at Module._compile (internal/modules/cjs/loader.js:1032:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
at Module.load (internal/modules/cjs/loader.js:933:32)
at Function.Module._load (internal/modules/cjs/loader.js:774:14)
at Module.require (internal/modules/cjs/loader.js:957:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (c:\Users\Flavio\Documents\Coding\projects-my\study-content\study-luiz-miranda\node\app.js:1:24)
at Module._compile (internal/modules/cjs/loader.js:1068:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
const fs = require('fs').promises;
const path = require('path');
exports.deleteFile = async (dir, file) => new Promise((resolve, reject) => {
let deletedFile = await fs.unlink(path.join(dir, file), (err) => {
if (err) return reject(err);
});
resolve(console.log('Deleted'))
})
解决方案
你应该更好地理解承诺
const fs = require('fs').promises;
const path = require('path');
exports.deleteFile = async (dir, file) => {
await fs.unlink(path.join(dir, file))
console.log('Deleted')
}
async/await 函数总是返回一个 promise。
推荐阅读
- python - Pandas:如何仅删除列末尾的最后一个连字符
- google-forms - 如何根据其他用户过去的回复使 Google 表单自动填充?
- c - 我知道一个地址,但我应该如何判断在哪个部分?使用C的全局区域或堆区域或堆栈区域
- json - 如何解决“手势 RangeError(索引)捕获的异常:无效值:有效值范围为空:0”
- c++ - 什么会使多边形算法中的点仅在正向和反向运行时才能正常工作?
- php - PHP:如何使用键->值对每两个分隔符将一个字符串分解为一个数组
- kubernetes - 将 GKE 集群拆除为“全新”状态而不删除它?
- scala - Spark——自定义reduce函数保存到磁盘然后上传到s3
- javascript - XMLHttpRequest 返回事件对象而不是实际数据
- fortran - Fortran 将未知大小的文件读入数组