NodeJs: fs.unlink does not delete file [VS]

Viewed 9746

I am aware this isn't the first post about fs.unlink not working, but I'm very new to both Visual Studio and Node Js.

I want to delete a file in the working folder, I got an error and the file is not deleted.

Here is what I tried:

var fs = require('fs');
fs.unlink('test1.txt');

PS: I installed the necessary Node Js components in VS.

1 Answers

As far as the code goes, you're not invoking fs.unlink properly. For starters, it's asynchronous. You will need to provide it a callback. See example here:

https://nodejs.org/api/fs.html#fs_fs_unlink_path_callback

Secondly, you need to provide it the full file path, not just the name of the file... ie:

var fs = require('fs');
fs.unlink('C:\path\to\my\file\test1.txt', (err) => {});

You can also supply it with the variable __dirname to utilize your current working directory from wherever you invoke node against the script. Thus, that would look something like:

let fs = require('fs');
let path = require('path');

fs.unlink(path.join(__dirname, 'test1.txt', (err) => {
  if (err) throw err;
  console.log('test1.txt was deleted');
});

Currently, you can also invoke it synchronously using it's single parameter signature... thus you'd provide only the dir path:

fs.unlinkSync('C:\\path\\to\\my\\file\\test1.txt');

But, this is ill-advised as it will be blocking. I'd only use the "sync" variant during some application bootstrapping process, where it'd be invoked only one time or so, at startup. Try to fight the urge of it being "easier" to use and understand, and instead get yourself to understand asynchronous logic.

Related