How to remove a file synchronously using Node.js?

Published December 21, 2020

To remove a file, we can use the unlinkSync() function from the fs (filesystem) module Node.js. This will synchronously remove the file.

// Remove file synchronously
fs.unlinkSync("file.txt");

For exampe let's consider a file called file.txt like this,

// require fs module
const fs = require("fs");

// path
const path = "file.txt";

Now let's use the fs.unlinkSync() function and

  • pass the path as the first argument

to the function like this,

// require fs module
const fs = require("fs");

// path
const path = "file.txt";

// remove file by passing path
// as the first argument to the function
fs.unlinkSync(path);

See this example live in repl.it.

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter