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
const fs = require( 'fs' );
fs.symlinkSync(__dirname + "\\example_file.txt" ,
"symlinkToFile" , 'file' );
console.log( "\nSymlink created\n" );
fs.readlink( "symlinkToFile" , (err, linkString) => {
if (err)
console.log(err);
else
console.log( "Path of the symlink:" , linkString);
});
fs.readlink( "symlinkToFile" ,
{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
const fs = require( 'fs' );
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
Share your thoughts in the comments
Please Login to comment...