Skip to content
Related Articles
Open in App
Not now

Related Articles

Node.js fs.unlinkSync() Method

Improve Article
Save Article
  • Last Updated : 08 Oct, 2021
Improve Article
Save Article

The fs.unlinkSync() method is used to synchronously remove a file or symbolic link from the filesystem. This function does not work on directories, therefore it is recommended to use fs.rmdir() to remove a directory.
Syntax:  

fs.unlinkSync( path )

Parameters: This method accepts one parameter as mentioned above and described below:  

  • path: It is a string, Buffer or URL which represents the file or symbolic link which has to be removed.

Below examples illustrate the fs.unlinkSync() method in Node.js:
Example 1: This example removes a file from the filesystem.

javascript




// Node.js program to demonstrate the
// fs.unlinkSync() method
  
// Import the filesystem module
const fs = require('fs');
  
// Get the files in current directory
// before deletion
getFilesInDirectory();
  
// Delete readme.md
fs.unlinkSync("readme.md");
console.log("\nFile readme.md is deleted");
  
// Get the files in current directory
// after deletion
getFilesInDirectory();
  
// Function to get current filenames
// in directory with specific extension
function getFilesInDirectory() {
  console.log("\nFiles present in directory:");
  let files = fs.readdirSync(__dirname);
  files.forEach(file => {
    console.log(file);
  });
}

Output: 

Files present in directory:
index.html
index.js
package.json
readme.md

File readme.md is deleted

Files present in directory:
index.html
index.js
package.json

Example 2: This example removes a symbolic link from the filesystem. 

javascript




// Node.js program to demonstrate the
// fs.unlinkSync() method
  
// Import the filesystem module
const fs = require('fs');
  
// Creating symlink to file
fs.symlinkSync(__dirname + "\\readme.md", "symlinkToReadme");
console.log("\nSymbolic link to readme.md created");
  
// Function to get current filenames
// in directory with specific extension
getFilesInDirectory();
  
// Deleting symbolic link to readme.md
fs.unlinkSync("symlinkToReadme");
console.log("\nSymbolic link to readme.md deleted")
  
getFilesInDirectory();
  
// Function to get current filenames
// in directory with specific extension
function getFilesInDirectory() {
  console.log("\nFiles present in directory:");
  let files = fs.readdirSync(__dirname);
  files.forEach(file => {
    console.log(file);
  });
}

Output: 

Symbolic link to readme.md created

Files present in directory:
index.html
index.js
package.json
readme.md
symlinkToReadme

Symbolic link to readme.md deleted

Files present in directory:
index.html
index.js
package.json
readme.md

Reference: https://nodejs.org/api/fs.html#fs_fs_unlinksync_path


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!