Skip to content

How to remove a file with Node.js

Discover how to remove a file from the filesystem with Node.js

How do you remove a file from the filesytem using Node.js?

Node offers a synchronous method, and an asynchronous method through the fs built-in module.

The asynchronous one is fs.unlink().

The synchronous one is fs.unlinkSync().

The difference is simple: the synchronous call will cause your code to block and wait until the file has been removed. The asynchronous one will not block your code, and will call a callback function once the file has been deleted.

Here's how to use those 2 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 my free Node.js Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about node: