Node.js fs.promises.link() Method

The fs.promises.link() method is an inbuilt application programming interface of the fs.promises class which is used to make a new name for a file.

Syntax:

fs.promises.link(existing_path, new_path);

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

  • existing_path: It is a required parameter specifies a string/URL/Buffer which denotes the existing path of the file.
  • new_path: It is a required parameter specifies a string/URL/Buffer which denotes the new path for the file.

Return Value: It returns a promise. If the linking is successful the promise is resolved with no value, otherwise rejected with an error object.

Below examples illustrate the use of fs.promises.link() method in Node.js:



Example 1::

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Accessing fs module
const fs = require('fs');
const fsPromises = fs.promises;
  
// fs.promises link 
fsPromises.link('./filename.txt','../filename.txt')
  .then(() => console.log('linked successfully'))
  .catch(() => console.error('failed to link!'));

chevron_right


Output:

(node:5052) ExperimentalWarning: The fs.promises API is experimental
linked successfully

Example 2:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Accessing fs module
const {
  promises: fsPromises
} = require('fs');
  
// Not work for directory
// fs.promises link 
fsPromises.link('../dir_name','./dir_name')
  .then(() => console.log('linked successfully'))
  .catch(() => console.error('failed to link!'));

chevron_right


Output:

(node:11936) ExperimentalWarning: The fs.promises API is experimental
failed to link!

Note: The above program will compile and run by using the node filename.js command and use the file_path correctly.

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

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.