rename a file in javascript

Renaming a file in JavaScript can be achieved using the fs.rename() method from the fs module in Node.js. This method takes two arguments: the current filename and the new filename. Here's an example:

index.tsx
const fs = require('fs');

fs.rename('currentFile.txt', 'newFile.txt', function (err) {
  if (err) throw err;
  console.log('File renamed successfully');
});
158 chars
7 lines

In the example above, we're renaming a file called currentFile.txt to newFile.txt. The fs.rename() method is asynchronous, so we pass it a callback function that will be executed once the file has been renamed. If any error occurs during the renaming process, it will be thrown.

Note that you can also use the fs.promises.rename() method if you want to work with promises instead of callbacks. Here's how you can use it:

index.tsx
const fsPromises = require('fs').promises;

fsPromises.rename('currentFile.txt', 'newFile.txt')
  .then(() => console.log('File renamed successfully'))
  .catch((err) => console.error('Error occurred while renaming file', err));
229 chars
6 lines

gistlibby LogSnag