How to delete files using Node.js

Explore how to delete files from the file system using Node.js

How to delete files from the file system using Node.js?

The node provides a synchronization method, and throughfsBuilt-in modules.

Asynchronous isfs.unlink().

Synchronized isfs.unlinkSync().

The difference is simple: synchronous calls will cause your code to block and wait until the file is deleted. Asynchronous code will not block your code, and the callback function will be called after the file is deleted.

This is how to use these two functions:

fs.unlinkSync():

const fs = require('fs')

const path = ‘./file.txt’

try { fs.unlinkSync(path) //file removed } catch(err) { console.error(err) }

fs.unlink():

const fs = require('fs')

const path = ‘./file.txt’

fs.unlink(path, (err) => { if (err) { console.error(err) return }

//file removed })

Download mine for freeNode.js manual


More node tutorials: