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 */ });
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);
}
}
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.
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")
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')
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();
}
);
}
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();
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.
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!")
})
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');
});
With the help of below URL, you can either copy or move your file CURRENT Source to Destination Source
/*********Moves the $file to $dir2 Start *********/_x000D_
var moveFile = (file, dir2)=>{_x000D_
//include the fs, path modules_x000D_
var fs = require('fs');_x000D_
var path = require('path');_x000D_
_x000D_
//gets file name and adds it to dir2_x000D_
var f = path.basename(file);_x000D_
var dest = path.resolve(dir2, f);_x000D_
_x000D_
fs.rename(file, dest, (err)=>{_x000D_
if(err) throw err;_x000D_
else console.log('Successfully moved');_x000D_
});_x000D_
};_x000D_
_x000D_
//move file1.htm from 'test/' to 'test/dir_1/'_x000D_
moveFile('./test/file1.htm', './test/dir_1/');_x000D_
/*********Moves the $file to $dir2 END *********/_x000D_
_x000D_
/*********copy the $file to $dir2 Start *********/_x000D_
var copyFile = (file, dir2)=>{_x000D_
//include the fs, path modules_x000D_
var fs = require('fs');_x000D_
var path = require('path');_x000D_
_x000D_
//gets file name and adds it to dir2_x000D_
var f = path.basename(file);_x000D_
var source = fs.createReadStream(file);_x000D_
var dest = fs.createWriteStream(path.resolve(dir2, f));_x000D_
_x000D_
source.pipe(dest);_x000D_
source.on('end', function() { console.log('Succesfully copied'); });_x000D_
source.on('error', function(err) { console.log(err); });_x000D_
};_x000D_
_x000D_
//example, copy file1.htm from 'test/dir_1/' to 'test/'_x000D_
copyFile('./test/dir_1/file1.htm', './test/');_x000D_
/*********copy the $file to $dir2 END *********/
_x000D_
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.
Use the mv node module which will first try to do an fs.rename
and then fallback to copying and then unlinking.
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.
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!');
Source: Stackoverflow.com