2023-05-22 05:00:06

Node.js删除文件

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

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

我没有看到删除命令?


当前回答

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

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

其他回答

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。

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

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

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

从filename匹配regexp的目录中删除文件。只使用fs。Unlink -删除文件,fs。Readdir -从目录中获取所有文件

var fs = require('fs');
const path = '/path_to_files/filename.anyextension'; 

const removeFile = (fileName) => {
    fs.unlink(`${path}${fileName}`, function(error) {
        if (error) {
            throw error;
        }
        console.log('Deleted filename', fileName);
    })
}

const reg = /^[a-zA-Z]+_[0-9]+(\s[2-4])+\./

fs.readdir(path, function(err, items) {
    for (var i=0; i<items.length; i++) {
        console.log(items[i], ' ', reg.test(items[i]))
        if (reg.test(items[i])) {
           console.log(items[i])
           removeFile(items[i]) 
        }
    }
});

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

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.'));
  }
});