2023-05-22 05:00:06

Node.js删除文件

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

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

我没有看到删除命令?


当前回答

简单且同步

if (fs.existsSync(pathToFile)) {
  fs.unlinkSync(pathToFile)
}

其他回答

简单且同步

if (fs.existsSync(pathToFile)) {
  fs.unlinkSync(pathToFile)
}

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。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很简单。

var fs = require('fs');
try{
 var sourceUrls = "/sampleFolder/sampleFile.txt";
 fs.unlinkSync(sourceUrls);
}catch(err){
 console.log(err);
}

2020的答案

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

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

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