node.js remove file

前端 未结 17 1508
误落风尘
误落风尘 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:27

    2019 and Node 10+ is here. Below the version using sweet async/await way.

    Now no need to wrap fs.unlink into Promises nor to use additional packages (like fs-extra) anymore.

    Just use native fs Promises API.

    const fs = require('fs').promises;
    
    (async () => {
      try {
        await fs.unlink('~/any/file');
      } catch (e) {
        // file doesn't exist, no permissions, etc..
        // full list of possible errors is here 
        // http://man7.org/linux/man-pages/man2/unlink.2.html#ERRORS
        console.log(e);
      }
    })();
    

    Here is fsPromises.unlink spec from Node docs.

    Also please note that fs.promises API marked as experimental in Node 10.x.x (but works totally fine, though), and no longer experimental since 11.14.0.

提交回复
热议问题