Node.js fs.renameSync() Method
Last Updated :
12 Oct, 2021
The fs.renameSync() method is used to synchronously rename a file at the given old path to the given new path. It will overwrite the destination file if it already exists.
Syntax:
fs.renameSync( oldPath, newPath )
Property Values:
- oldPath: It holds the path of the file that has to be renamed. It can be a string, buffer or URL.
- newPath: It holds the new path that the file has to be renamed to. It can be a string, buffer or URL.
Below examples illustrate the fs.renameSync() method in Node.js:
Example 1: This example uses fs.renameSync() method to rename a file.
const fs = require( 'fs' );
getCurrentFilenames();
fs.renameSync( 'hello.txt' , 'world.txt' );
getCurrentFilenames();
function getCurrentFilenames() {
console.log( "Current filenames:" );
fs.readdirSync(__dirname).forEach(file => {
console.log(file);
});
}
|
Output:
Current filenames:
hello.txt
index.js
package.json
Current filenames:
index.js
package.json
world.txt
Example 2: This example uses fs.renameSync() method to demonstrate an error during file renaming.
const fs = require( 'fs' );
getCurrentFilenames();
fs.renameSync( 'nonexist.txt' , 'world.txt' );
getCurrentFilenames();
function getCurrentFilenames() {
console.log( "Current filenames:" );
fs.readdirSync(__dirname).forEach(file => {
console.log(file);
});
}
|
Output:
Current filenames:
index.js
package.json
world.txt
internal/fs/utils.js:220
throw err;
^
Error: ENOENT: no such file or directory, rename 'nonexist.txt' -> 'world.txt'
at Object.renameSync (fs.js:643:3)
at Object. (G:\tutorials\nodejs-fs-renameSync\index.js:29:4)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
at internal/main/run_main_module.js:17:11 {
errno: -4058,
syscall: 'rename',
code: 'ENOENT',
path: 'nonexist.txt',
dest: 'world.txt'
}
Reference: https://nodejs.org/api/fs.html#fs_fs_renamesync_oldpath_newpath
Share your thoughts in the comments
Please Login to comment...