Open In App

Node.js fs.readlink() Method

The fs.readlink() method is an inbuilt application programming interface of fs module which is used to asynchronously return a symbolic link’s value, i.e. the path it is linked to. The optional argument can be used to specify the character encoding of the link path.

Syntax:



fs.readlink( path[, options], callback )

Parameters: This method accepts three parameters as mentioned above and described below: 

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



Example 1: This example reads the value of symlink for a file and also changes the encoding of the value.




// Node.js program to demonstrate the
// fs.readlink() method
  
// Import the filesystem module
const fs = require('fs');
  
// Create a symbolic link
fs.symlinkSync(__dirname + "\\example_file.txt"
                       "symlinkToFile", 'file');
  
console.log("\nSymlink created\n");
  
// Using the default utf-8 encoding for the link value
fs.readlink("symlinkToFile", (err, linkString) => {
  if (err)
    console.log(err);
  else
    console.log("Path of the symlink:", linkString);
});
  
  
// Using the base64 encoding for the link value
fs.readlink("symlinkToFile"
  
  // Specify the options object
  {encoding: "base64"},
  (err, linkString) => {
    if (err)
      console.log(err);
    else
      console.log("Path in base64:", linkString);
});

Output:

Symlink created

Path of the symlink: G:\tutorials\nodejs-fs-readlink\example_file.txt
Path in base64: RzpcdHV0b3JpYWxzXG5vZGVqcy1mcy1yZWFkbGlua1xleGFtcGxlX2ZpbGUudHh0

Example 2: This example reads the value of a symlink for a directory.




// Node.js program to demonstrate the
// fs.readlink() method
  
// Import the filesystem module
const fs = require('fs');
  
// Create a symbolic link
fs.symlinkSync(__dirname + "\\example_directory"
            "symlinkToDir", 'dir');
  
console.log("\nSymlink created\n");
  
fs.readlink("symlinkToDir", (err, linkString) => {
  if (err)
    console.log(err);
  else
    console.log("Path of the symlink:", linkString);
});

Output:

Symlink created

Path of the symlink: G:\tutorials\nodejs-fs-readlink\example_directory

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


Article Tags :