我如何删除一个文件与node.js?
http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback
我没有看到删除命令?
我如何删除一个文件与node.js?
http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback
我没有看到删除命令?
当前回答
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。
其他回答
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。
fs.unlinkSync()如果你想同步删除文件 Fs.unlink()如果你想异步删除它。
在这里你可以找到一篇好文章。
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的信息可以在这里找到。
你可以调用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);