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)用于异步断开(2)或fs.unlinkSync(path)用于同步断开(2)。 path是你要删除的file-path。

例如,我们想从c:/book目录中删除discovery.docx文件。我的文件路径是c:/book/discovery。docx。删除文件的代码是,

var fs = require('fs');
var filePath = 'c:/book/discovery.docx'; 
fs.unlinkSync(filePath);

其他回答

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。Unlink将为您检查。

fs.unlink('fileToBeRemoved', function(err) {
    if(err && err.code == 'ENOENT') {
        // file doens't exist
        console.info("File doesn't exist, won't remove it.");
    } else if (err) {
        // other errors, e.g. maybe we don't have enough permission
        console.error("Error occurred while trying to remove file");
    } else {
        console.info(`removed`);
    }
});

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

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

你可以做下面的事情

const deleteFile = './docs/deleteme.txt'
if (fs.existsSync(deleteFile)) {
    fs.unlink(deleteFile, (err) => {
        if (err) {
            console.log(err);
        }
        console.log('deleted');
    })
}

异步删除文件或符号链接。除了一个可能的异常外,没有其他参数被提供给完成回调。

Fs.unlink()将不能在空目录或其他目录上工作。要删除一个目录,请使用fs.rmdir()。

更多的细节

下面是我的代码,工作正常。

         const fs = require('fs');
         fs.unlink(__dirname+ '/test.txt', function (err) {            
              if (err) {                                                 
                  console.error(err);                                    
              }                                                          
             console.log('File has been Deleted');                           
          });