The fs.link() method is used to create a hard link to the given path. The hard link created would still point to the same file even if the file is renamed. The hard links also contain the actual contents of the linked file.
Syntax:
fs.link( existingPath, newPath, callback )
Parameters: This method accepts three 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.
- callback: It is a function that would be called when the method is executed.
- err: It is an error that would be thrown if the method fails.
Below examples illustrate the fs.link() 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.link(__dirname + "\\example_file.txt" , "hardlinkToFile" , (err) => {
if (err) console.log(err)
else {
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:
This is an example of the fs.link() method.
Hard link created
Contents of the hard created:
This is an example of the fs.link() method.
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.link(__dirname + "\\example_file.txt" , "hardlinkToFile" , (err) => {
if (err) console.log(err)
else {
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:
This is an example of the fs.link() method.
Hard link created
Contents of the hard link created:
This is an example of the fs.link() method.
Deleting the original file
Contents of the hard link created:
This is an example of the fs.link() method.
Reference: https://nodejs.org/api/fs.html#fs_fs_link_existingpath_newpath_callback
Last Updated :
08 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...