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.