Node.js fs.unlinkSync() Method
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
const fs = require( 'fs' );
getFilesInDirectory();
fs.unlinkSync( "readme.md" );
console.log( "\nFile readme.md is deleted" );
getFilesInDirectory();
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
const fs = require( 'fs' );
fs.symlinkSync(__dirname + "\\readme.md" , "symlinkToReadme" );
console.log( "\nSymbolic link to readme.md created" );
getFilesInDirectory();
fs.unlinkSync( "symlinkToReadme" );
console.log( "\nSymbolic link to readme.md deleted" )
getFilesInDirectory();
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
Last Updated :
08 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...