How do I move files in node.js?

May 2024 · 6 minute read

How can I move files (like mv command shell) on node.js? Is there any method for that or should I read a file, write to a new file and remove older file?

0

17 Answers

According to seppo0010 comment, I used the rename function to do that.

http://nodejs.org/docs/latest/api/fs.html#fs_fs_rename_oldpath_newpath_callback

fs.rename(oldPath, newPath, callback)

Added in: v0.0.2

oldPath <String> | <Buffer> newPath <String> | <Buffer> callback <Function> 

Asynchronous rename(2). No arguments other than a possible exception are given to the completion callback.

2

Using nodejs natively

var fs = require('fs') var oldPath = 'old/path/file.txt' var newPath = 'new/path/file.txt' fs.rename(oldPath, newPath, function (err) { if (err) throw err console.log('Successfully renamed - AKA moved!') }) 

(NOTE: "This will not work if you are crossing partitions or using a virtual filesystem not supporting moving files. [...]" – Flavien Volken Sep 2 '15 at 12:50")

This example taken from: Node.js in Action

A move() function that renames, if possible, or falls back to copying

var fs = require('fs'); module.exports = function move(oldPath, newPath, callback) { fs.rename(oldPath, newPath, function (err) { if (err) { if (err.code === 'EXDEV') { copy(); } else { callback(err); } return; } callback(); }); function copy() { var readStream = fs.createReadStream(oldPath); var writeStream = fs.createWriteStream(newPath); readStream.on('error', callback); writeStream.on('error', callback); readStream.on('close', function () { fs.unlink(oldPath, callback); }); readStream.pipe(writeStream); } } 
6

Use the mv node module which will first try to do an fs.rename and then fallback to copying and then unlinking.

3

util.pump is deprecated in node 0.10 and generates warning message

 util.pump() is deprecated. Use readableStream.pipe() instead 

So the solution for copying files using streams is:

var source = fs.createReadStream('/path/to/source'); var dest = fs.createWriteStream('/path/to/dest'); source.pipe(dest); source.on('end', function() { /* copied */ }); source.on('error', function(err) { /* error */ }); 
1

The fs-extra module allows you to do this with it's move() method. I already implemented it and it works well if you want to completely move a file from one directory to another - ie. removing the file from the source directory. Should work for most basic cases.

var fs = require('fs-extra') fs.move('/tmp/somefile', '/tmp/does/not/exist/yet/somefile', function (err) { if (err) return console.error(err) console.log("success!") }) 
2

Using promises for Node versions greater than 8.0.0:

const {promisify} = require('util'); const fs = require('fs'); const {join} = require('path'); const mv = promisify(fs.rename); const moveThem = async () => { // Move file ./bar/foo.js to ./baz/qux.js const original = join(__dirname, 'bar/foo.js'); const target = join(__dirname, 'baz/qux.js'); await mv(original, target); } moveThem(); 
4

Using the rename function:

fs.rename(getFileName, __dirname + '/new_folder/' + getFileName); 

where

getFilename = file.extension (old path) __dirname + '/new_folder/' + getFileName 

assumming that you want to keep the file name unchanged.

1

Here's an example using util.pump, from >> How do I move file a to a different partition or device in Node.js?

var fs = require('fs'), util = require('util'); var is = fs.createReadStream('source_file') var os = fs.createWriteStream('destination_file'); util.pump(is, os, function() { fs.unlinkSync('source_file'); }); 
4

Just my 2 cents as stated in the answer above : The copy() method shouldn't be used as-is for copying files without a slight adjustment:

function copy(callback) { var readStream = fs.createReadStream(oldPath); var writeStream = fs.createWriteStream(newPath); readStream.on('error', callback); writeStream.on('error', callback); // Do not callback() upon "close" event on the readStream // readStream.on('close', function () { // Do instead upon "close" on the writeStream writeStream.on('close', function () { callback(); }); readStream.pipe(writeStream); } 

The copy function wrapped in a Promise:

function copy(oldPath, newPath) { return new Promise((resolve, reject) => { const readStream = fs.createReadStream(oldPath); const writeStream = fs.createWriteStream(newPath); readStream.on('error', err => reject(err)); writeStream.on('error', err => reject(err)); writeStream.on('close', function() { resolve(); }); readStream.pipe(writeStream); }) 

However, keep in mind that the filesystem might crash if the target folder doesn't exist.

I would separate all involved functions (i.e. rename, copy, unlink) from each other to gain flexibility and promisify everything, of course:

const renameFile = (path, newPath) => new Promise((res, rej) => { fs.rename(path, newPath, (err, data) => err ? rej(err) : res(data)); }); const copyFile = (path, newPath, flags) => new Promise((res, rej) => { const readStream = fs.createReadStream(path), writeStream = fs.createWriteStream(newPath, {flags}); readStream.on("error", rej); writeStream.on("error", rej); writeStream.on("finish", res); readStream.pipe(writeStream); }); const unlinkFile = path => new Promise((res, rej) => { fs.unlink(path, (err, data) => err ? rej(err) : res(data)); }); const moveFile = (path, newPath, flags) => renameFile(path, newPath) .catch(e => { if (e.code !== "EXDEV") throw new e; else return copyFile(path, newPath, flags) .then(() => unlinkFile(path)); }); 

moveFile is just a convenience function and we can apply the functions separately, when, for example, we need finer grained exception handling.

Shelljs is a very handy solution.

command: mv([options ,] source, destination)

Available options:

-f: force (default behaviour)

-n: to prevent overwriting

const shell = require('shelljs'); const status = shell.mv('README.md', '/home/my-dir'); if(status.stderr) console.log(status.stderr); else console.log('File moved!'); 
1

this is a rehash of teoman shipahi's answer with a slightly less ambiguous name, and following the design priciple of defining code before you attempt to call it. (Whilst node allows you to do otherwise, it's not good a practice to put the cart before the horse.)

function rename_or_copy_and_delete (oldPath, newPath, callback) { function copy_and_delete () { var readStream = fs.createReadStream(oldPath); var writeStream = fs.createWriteStream(newPath); readStream.on('error', callback); writeStream.on('error', callback); readStream.on('close', function () { fs.unlink(oldPath, callback); } ); readStream.pipe(writeStream); } fs.rename(oldPath, newPath, function (err) { if (err) { if (err.code === 'EXDEV') { copy_and_delete(); } else { callback(err); } return;// << both cases (err/copy_and_delete) } callback(); } ); } 

If you are trying to move or rename a node.js source file, try this https://github.com/viruschidai/node-mv. It will update the references to that file in all other files.

With the help of below URL, you can either copy or move your file CURRENT Source to Destination Source

https://coursesweb.net/nodejs/move-copy-file

/*********Moves the $file to $dir2 Start *********/ var moveFile = (file, dir2)=>{ //include the fs, path modules var fs = require('fs'); var path = require('path'); //gets file name and adds it to dir2 var f = path.basename(file); var dest = path.resolve(dir2, f); fs.rename(file, dest, (err)=>{ if(err) throw err; else console.log('Successfully moved'); }); }; //move file1.htm from 'test/' to 'test/dir_1/' moveFile('./test/file1.htm', './test/dir_1/'); /*********Moves the $file to $dir2 END *********/ /*********copy the $file to $dir2 Start *********/ var copyFile = (file, dir2)=>{ //include the fs, path modules var fs = require('fs'); var path = require('path'); //gets file name and adds it to dir2 var f = path.basename(file); var source = fs.createReadStream(file); var dest = fs.createWriteStream(path.resolve(dir2, f)); source.pipe(dest); source.on('end', function() { console.log('Succesfully copied'); }); source.on('error', function(err) { console.log(err); }); }; //example, copy file1.htm from 'test/dir_1/' to 'test/' copyFile('./test/dir_1/file1.htm', './test/'); /*********copy the $file to $dir2 END *********/

fs.rename is also available in the sync version:

fs.renameSync(oldPath, newPath) 

Node.js v10.0.0+

const fs = require('fs') const { promisify } = require('util') const pipeline = promisify(require('stream').pipeline) await pipeline( fs.createReadStream('source/file/path'), fs.createWriteStream('destination/file/path') ).catch(err => { // error handling }) fs.unlink('source/file/path') 

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJob25vaWWCdnvHqK5mnJ9itm65zq%2BcZp6ZobK0ecinZKenlJp6q78%3D