Open In App

Node.js fs.linksync() Method

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:

Below examples illustrate the fs.linkSync() method in Node.js:



Example 1: This example creates a hard link to a file.




// Node.js program to demonstrate the
// fs.linkSync() method
  
// Import the filesystem module
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.




// Node.js program to demonstrate the
// fs.linkSync() method
  
// Import the filesystem module
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


Article Tags :