DEV Community

Cover image for How to remove a file synchronously using Node.js?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to remove a file synchronously using Node.js?

Originally posted here!

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");
Enter fullscreen mode Exit fullscreen mode

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

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

// path
const path = "file.txt";
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

See this example live in repl.it.

Feel free to share if you found this useful 😃.


Top comments (0)