Sometimes, we want to move files in Node.js.
In this article, we’ll look at how to move files in Node.js.
How to move files in Node.js?
To move files in Node.js, we can use the fs.rename
method.
For instance, we write
const fs = require('fs')
const oldPath = 'old/path/file.txt'
const newPath = 'new/path/file.txt'
fs.rename(oldPath, newPath, (err) => {
if (err) {
throw err
}
console.log('successfully moved')
})
to call rename
with the oldPath
of the file, newPath
of the file, and a callback that runs when the moving is done.
If there’s an error, err
will be set.
Conclusion
To move files in Node.js, we can use the fs.rename
method.