我如何删除一个文件与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
我没有看到删除命令?
当前回答
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。Stat或fs。statSync (Synchronous)而不是fs.exists。因为根据最新的node.js文档,fs。现在已弃用。
例如:-
fs.stat('./server/upload/my.csv', function (err, stats) {
console.log(stats);//here we got all information of file in stats variable
if (err) {
return console.error(err);
}
fs.unlink('./server/upload/my.csv',function(err){
if(err) return console.log(err);
console.log('file deleted successfully');
});
});
您可以使用del模块删除当前目录中的一个或多个文件。它的好处是可以保护您不删除当前工作目录和以上目录。
const del = require('del');
del(['<your pathere here>/*']).then( (paths: any) => {
console.log('Deleted files and folders:\n', paths.join('\n'));
});
我认为你应该使用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()。
更多的细节
你可以使用fs。Unlink (path, callback)函数。下面是一个带有"error-back"模式的函数包装器示例:
/ /依赖性。 Const fs = require('fs'); //删除文件 const deleteFile = (filePath, callback) => { //断开文件链接。 fs。unlink(filePath, (error) => { If(!错误){ 回调(假); }其他{ callback('删除文件错误'); } }) };