node.js remove file

前端 未结 17 1457
误落风尘
误落风尘 2020-12-07 06:54

How do I delete a file with node.js?

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

I don\'t see a remove command?

相关标签:
17条回答
  • 2020-12-07 07:34

    Use NPM module fs-extra, which gives you everything in fs, plus everything is Promisified. As a bonus, there's a fs.remove() method available.

    0 讨论(0)
  • 2020-12-07 07:36

    I think you want to use fs.unlink.

    More info on fs can be found here.

    0 讨论(0)
  • 2020-12-07 07:37
    • fs.unlinkSync() if you want to remove files synchronously and
    • fs.unlink() if you want to remove it asynchronously.

    Here you can find a good article.

    0 讨论(0)
  • 2020-12-07 07:38

    Simple and sync

    if (fs.existsSync(pathToFile)) {
      fs.unlinkSync(pathToFile)
    }
    
    0 讨论(0)
  • 2020-12-07 07:39

    If you want to check file before delete whether it exist or not. So, use fs.stat or fs.statSync (Synchronous) instead of fs.exists. Because according to the latest node.js documentation, fs.exists now deprecated.

    For example:-

     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');
       });  
    });
    
    0 讨论(0)
  • 2020-12-07 07:39

    I don't think you have to check if file exists or not, fs.unlink will check it for you.

    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`);
        }
    });
    
    0 讨论(0)
提交回复
热议问题