Categories
JavaScript Answers Nodejs

How to Move Files in Node.js Apps?

Spread the love

To move files in our Node.js apps, we can use the fs.rename method.

For instance, we can write:

const fs = require('fs')

const oldPath = 'old/file.txt'
const newPath = 'new/file.txt'

fs.rename(oldPath, newPath, (err) => {
  if (err) throw err
  console.log('Successfully renamed - AKA moved!')
})

to import the fs module with:

const fs = require('fs')

Then we specify the oldPath and newPath to set the source and destination file paths respectively.

Next, we call fs.rename with the oldPath and newPath to move the file from oldPath to newPath .

The 3rd argument is a callback that will be run when the file moving operation is done.

If there’re any errors, then err will be defined.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *