2023-05-22 05:00:06

Node.js删除文件

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

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

我没有看到删除命令?


当前回答

作为公认的答案,使用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');
});

其他回答

使用NPM模块fs-extra,它提供了fs中的所有内容,加上所有内容都是承诺的。另外,还有一个fs.remove()方法可用。

2019年和节点10+已经到来。下面的版本采用了甜异步/等待的方式。

现在不需要对fs进行换行。不再链接到Promises,也不再使用额外的包(比如fs-extra)。

只需使用本地fs承诺API。

const fs = require('fs').promises;

(async () => {
  try {
    await fs.unlink('~/any/file');
  } catch (e) {
    // file doesn't exist, no permissions, etc..
    // full list of possible errors is here 
    // http://man7.org/linux/man-pages/man2/unlink.2.html#ERRORS
    console.log(e);
  }
})();

这里是fsPromises。从Node文档中断开规范链接。

另外,请注意fs。在Node 10.x中承诺API标记为实验性。X(但是工作完全正常),并且从11.14.0开始不再是实验性的。

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

您可以使用del模块删除当前目录中的一个或多个文件。它的好处是可以保护您不删除当前工作目录和以上目录。

const del = require('del');
del(['<your pathere here>/*']).then( (paths: any) => {
   console.log('Deleted files and folders:\n', paths.join('\n'));
});

2020的答案

有了节点v14.14.0的发行版,您现在就可以这样做了。

fs.rmSync("path/to/file", {
    force: true,
});

https://nodejs.org/api/fs.html#fsrmsyncpath-options