2023-05-22 05:00:06

Node.js删除文件

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

http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_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

其他回答

你可以做下面的事情

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()。

更多的细节

这是我为此制作的一个小片段,

var fs = require('fs');
var gutil = require('gulp-util');

fs.exists('./www/index.html', function(exists) {
  if(exists) {
    //Show in green
    console.log(gutil.colors.green('File exists. Deleting now ...'));
    fs.unlink('./www/index.html');
  } else {
    //Show in red
    console.log(gutil.colors.red('File not found, so not deleting.'));
  }
});

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.unlinkSync()如果你想同步删除文件 Fs.unlink()如果你想异步删除它。

在这里你可以找到一篇好文章。

你可以调用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);