Node.js fs.readlink() Method
Last Updated :
29 Jul, 2020
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:
- path: It is a string, Buffer, or URL which represents the path of the symbolic link.
- options: It is an object or string that can be used to specify optional parameters that will affect the output. It has one optional parameter:
- encoding: It is a string value that specifies the character encoding in which the link path is returned. The default value is 'utf8'.'
- callback: It is the function that would be called when the method is executed.
- err: It is an error that would be thrown if the method fails.
- linkString: It is the string or Buffer object that contains the symbolic link's string value.
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.
javascript
// 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.
javascript
// 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
Explore
Introduction & Installation
Node.js Modules , Buffer & Streams
Node.js Asynchronous Programming
Node.js NPM
Node.js Deployments & Communication
Resources & Tools