Node.js fs.linksync() Method
Last Updated :
11 Oct, 2021
The fs.linkSync() method is used to synchronously create a hard link to the specified path. The hard link created would still point to the same file even if the file is renamed. The hard links also have the actual file contents of the linked file.
Syntax:
fs.linkSync( existingPath, newPath )
Parameters: This method accept two parameters as mentioned above and described below:
- existingPath: It is a string, buffer or URL which represents the file to which the symlink has to be created.
- newPath: It is a string, buffer or URL which represents the file path where the symlink will be created.
Below examples illustrate the fs.linkSync() method in Node.js:
Example 1: This example creates a hard link to a file.
const fs = require( 'fs' );
console.log( "Contents of the text file:" );
console.log(fs.readFileSync( 'example_file.txt' , 'utf8' ));
fs.linkSync(__dirname + "\\example_file.txt" , "hardlinkToFile" , 'file' );
console.log( "\nHard link created\n" );
console.log( "Contents of the hard link created:" );
console.log(fs.readFileSync( 'hardlinkToFile' , 'utf8' ));
|
Output:
Contents of the text file:
Hello GeeksForGeeks
Hard link created
Contents of the hard link created:
Hello GeeksForGeeks
Example 2: This example creates a hard link to a file and deletes the original file. The contents of the original file can be still accessed through the hard link.
const fs = require( 'fs' );
console.log( "Contents of the text file:" );
console.log(fs.readFileSync( 'example_file.txt' , 'utf8' ));
fs.linkSync(__dirname + "\\example_file.txt" , "hardlinkToFile" , 'file' );
console.log( "\nHard link created\n" );
console.log( "Contents of the hard link created:" );
console.log(fs.readFileSync( 'hardlinkToFile' , 'utf8' ));
console.log( "\nDeleting the original file" );
fs.unlinkSync( "example_file.txt" );
console.log( "\nContents of the hard link created:" );
console.log(fs.readFileSync( 'hardlinkToFile' , 'utf8' ));
|
Output:
Contents of the text file:
Hello GeeksForGeeks
Hard link created
Contents of the hard link created:
Hello GeeksForGeeks
Deleting the original file
Contents of the hard link created:
Hello GeeksForGeeks
Reference: https://nodejs.org/api/fs.html#fs_fs_linksync_existingpath_newpath
Share your thoughts in the comments
Please Login to comment...