![]() |
VOOZH | about |
In Node.js, the fs.renameSync() method is part of the built-in File System (fs) module and is used to rename or move files and directories synchronously. This method is useful when you need to quickly change a file's name or move it to a different directory synchronously. It blocks the execution of code until the file operation completes.
Syntax:
fs.renameSync( oldPath, newPath )Property Values:
The fs.renameSync() method can do two things:
Below examples illustrate the fs.renameSync() method in Node.js:
Example 1: This example uses fs.renameSync() method to rename a file.
Output:
Current filenames:
hello.txt
index.js
package.json
Current filenames:
index.js
package.json
world.txtExample 2: This example uses fs.renameSync() method to demonstrate an error during file renaming.
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'
}Node.js provides both synchronous (fs.renameSync()) and asynchronous (fs.rename()) methods for renaming files. The key difference is that the synchronous method blocks the event loop until the operation is complete, while the asynchronous method does not block, allowing other tasks to be processed in the meantime.
Asynchronous Example: fs.rename()
const fs = require('fs');
// Asynchronously renaming a file
fs.rename('oldFile.txt', 'newFile.txt', (err) => {
if (err) throw err;
console.log('File renamed successfully');
});
In this example, the operation is non-blocking, and Node.js can perform other tasks while waiting for the rename operation to complete.