Node.js 实现 fs 模块删除文件

1. 使用 fs.unlinkSync 同步删除文件

fs.unlinkSyncfs 模块提供的同步删除文件的方法。它会阻塞 Node.js 事件循环,直到文件删除操作完成。

const fs = require("fs");
const filePath = "path/to/your/file.txt";
try {
  fs.unlinkSync(filePath);
  console.log("文件删除成功");
} catch (error) {
  console.error("删除文件时出错:", error);
}

2. 使用 fs.unlink 异步回调删除文件

fs.unlinkfs 模块提供的异步删除文件的方法,通过回调函数处理删除操作的结果。

const fs = require("fs");
const filePath = "path/to/your/file.txt";
fs.unlink(filePath, (error) => {
  if (error) {
    console.error("删除文件时出错:", error);
  } else {
    console.log("文件删除成功");
  }
});

3. 使用 fs/promises 异步 Promise 删除文件

const fs = require("fs/promises");
const filePath = "path/to/your/file.txt";
async function deleteFile() {
  try {
    await fs.unlink(filePath);
    console.log("文件删除成功");
  } catch (error) {
    console.error("删除文件时出错:", error);
  }
}
deleteFile();

你可能感兴趣的:(node.js)