gpt4 book ai didi

javascript - 尝试使用 Node.js 删除文件。我应该异步使用 fs.unlink(path, callback) 还是同步 fs.unlinkSync(path)?

转载 作者:行者123 更新时间:2023-12-04 08:01:10 32 4
gpt4 key购买 nike

我有一个从数据库中删除产品条目的简单函数,现在我也试图删除该产品的图像文件。我检查了 Node.js 文件系统文档,发现了 2 个处理该问题的函数 - fs.unlink(path, callback)fs.unlinkSync(path) .我知道第一个是异步的,第二个是同步的,但我仍然不太确定应该使用哪个以及为什么。

module.exports.deleteProduct = async (req, res, next) => {
let productId = req.body.productId

try {
let product = await Product.destroy({
where: {
id: productId
}
})

res.status(200).json({
product: product
})
} catch (e) {
console.log(e)
res.status(500)
}
}

最佳答案

一些代码和一个想法给你:
正如其他人已经说过的,async优于sync ,因此您最终不会阻塞,即使除非您的 API 量非常高,否则可能无关紧要,如另一个答案所示。
您可以使用 fs promises API通过

const fs = require('fs').promises; //es5 OR
import { promises as fs } from 'fs'; //es6
以单行方式使用异步(非阻塞)API await .
特别提示:您 5 月 如果您未能取消链接目录,不希望您的 API 请求失败,因为您实际上从数据库中删除了产品。
// make sure you are using the promise API from fs
const fs = require('fs').promises;

module.exports.deleteProduct = async (req, res, next) => {
let productId = req.body.productId

try {
let product = await Product.destroy({
where: {
id: productId
}
})

try {
await fs.unlink('the/path/to/the/product/image');
} catch {
// you may want to handle a failure to delete separately
}

res.status(200).json({product: product})
} catch (e) {
console.log(e)
res.status(500)
}
}

关于javascript - 尝试使用 Node.js 删除文件。我应该异步使用 fs.unlink(path, callback) 还是同步 fs.unlinkSync(path)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66456409/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com