Open In App

Node.js fsPromises.symlink() Method

Last Updated : 08 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The fsPromises.symlink() method is used to create a symlink to the specified path then resolves the Promise with no arguments upon success. This creates a link making the path point to the target. The relative targets are relative to the link’s parent directory.

Syntax:

fsPromises.symlink( target, path, type )

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

  • target: It is a string, buffer or URL which represents the path to which the symlink has to be created.
  • path: It is a string, buffer or URL which represents the path where the symlink will be created.
  • type: It is a string which represents the type of symlink to be created. It can be specified with ‘file’, ‘dir’ or ‘junction’. If the target does not exist, ‘file’ will be used.

The type argument is only used on Windows platforms and can be one of ‘dir’, ‘file’, or ‘junction’. Windows junction points require the destination path to be absolute. When using ‘junction’, the target argument will automatically be normalized to absolute path.

Example: This example illustrates the fsPromises.symlink() method in Node.js:

Filename: index.js




// Node.js program to demonstrate the 
// fsPromises.symlink method 
    
// Import the filesystem module 
const fs = require('fs'); 
const fsPromises = fs.promises;
    
console.log("Contents of the text file:"); 
console.log(fs.readFileSync(
        'example_file.txt', 'utf8')); 
    
fsPromises.symlink(__dirname + 
    "\\example_file.txt", "symlinkToFile", 'file'
.then(function() {
  console.log("\nSymlink created\n"); 
  console.log("Contents of the symlink created:"); 
  console.log(fs.readFileSync('symlinkToFile', 'utf8')); 
})
.catch(function(error) {
  console.log(error);
});


Step to run this program: Run index.js file using the following command:

node index.js

Output:

Contents of the text file:
Hello Geeks

Symlink created

Contents of the symlink created:
Hello Geeks

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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads