Node.js / Delete content in file

前端 未结 2 1358
走了就别回头了
走了就别回头了 2021-02-03 17:30

I want to delete the content of a simple text file with node.js. Or replace the file with a new/empty one.

How can I achieve this in node?

相关标签:
2条回答
  • 2021-02-03 17:52

    fs.unlink is the call you need to delete a file. To replace it with different contents, just overwrite it with fs.writeFile.

    0 讨论(0)
  • 2021-02-03 18:15

    You are looking for fs.truncate or fs.writeFile

    Either of the following will work:

    const fs = require('fs')
    fs.truncate('/path/to/file', 0, function(){console.log('done')})
    

    or

    const fs = require('fs')
    fs.writeFile('/path/to/file', '', function(){console.log('done')})
    

    There are also synchronous versions of both functions that you should not use.

    0 讨论(0)
提交回复
热议问题