2023-05-22 05:00:06

Node.js删除文件

我如何删除一个文件与node.js?

http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback

我没有看到删除命令?


当前回答

你可以使用fs。Unlink (path, callback)函数。下面是一个带有"error-back"模式的函数包装器示例:

/ /依赖性。 Const fs = require('fs'); //删除文件 const deleteFile = (filePath, callback) => { //断开文件链接。 fs。unlink(filePath, (error) => { If(!错误){ 回调(假); }其他{ callback('删除文件错误'); } }) };

其他回答

2022的答案

不要在Nodejs中做任何同步操作

若要异步删除文件,

const { unlink } = require('fs/promises');
(async function(path) {
  try {
    await unlink(path);
    console.log(`successfully deleted ${path}`);
  } catch (error) {
    console.error('there was an error:', error.message);
}
})('/tmp/hello');

裁判:https://nodejs.org/api/fs.html # promise-example

建议在使用access或stat删除前检查文件是否存在

import { access, constants } from 'fs';

const file = 'package.json';

// Check if the file exists in the current directory.
access(file, constants.F_OK, (err) => {
  console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
});

裁判:https://nodejs.org/api/fs.html # fsaccesspath-mode-callback

Fs-extra提供了一个删除方法:

const fs = require('fs-extra')

fs.remove('/tmp/myfile')
.then(() => {
  console.log('success!')
})
.catch(err => {
  console.error(err)
})

https://github.com/jprichardson/node-fs-extra/blob/master/docs/remove.md

我认为你应该使用fs。unlink。

更多关于fs的信息可以在这里找到。

作为公认的答案,使用fs。断开链接删除文件。

但根据Node.js文档

不建议在调用fs.open()、fs.readFile()或fs.writeFile()之前使用fs.stat()检查文件是否存在。相反,用户代码应该直接打开/读取/写入文件,并在文件不可用时处理引发的错误。 要检查一个文件是否存在而不进行操作,建议使用fs.access()。

检查文件是否可以删除,使用fs。访问相反

fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => {
  console.log(err ? 'no access!' : 'can read/write');
});

rm -rf它

require("fs").rmSync(file_or_directory_path_existing_or_not, {recursive: true, force: true});
// Added in Node.js 14.14.0.

要求(fs)。rmSync或require("fs").rm。