Move File in ExpressJS/NodeJS Move File in ExpressJS/NodeJS express express

Move File in ExpressJS/NodeJS


Yes, fs.rename does not move file between two different disks/partitions. This is the correct behaviour. fs.rename provides identical functionality to rename(2) in linux.

Read the related issue posted here.

To get what you want, you would have to do something like this:

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 */ });


Another way is to use fs.writeFile. fs.unlink in callback will remove the temp file from tmp directory.

var oldPath = req.files.file.path;var newPath = ...;fs.readFile(oldPath , function(err, data) {    fs.writeFile(newPath, data, function(err) {        fs.unlink(oldPath, function(){            if(err) throw err;            res.send("File uploaded to: " + newPath);        });    }); }); 


Updated ES6 solution ready to use with promises and async/await:

function moveFile(from, to) {    const source = fs.createReadStream(from);    const dest = fs.createWriteStream(to);    return new Promise((resolve, reject) => {        source.on('end', resolve);        source.on('error', reject);        source.pipe(dest);    });}