Move File in ExpressJS/NodeJS

17,274

Solution 1

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

Solution 2

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

Solution 3

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

Solution 4

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);
}
}
Share:
17,274
JR Galia
Author by

JR Galia

I'm JR Galia.

Updated on June 03, 2022

Comments

  • JR Galia
    JR Galia almost 2 years

    I'm trying to move uploaded file from /tmp to home directory using NodeJS/ExpressJS:

    fs.rename('/tmp/xxxxx', '/home/user/xxxxx', function(err){
        if (err) res.json(err);
    
    console.log('done renaming');
    });
    

    But it didn't work and no error encountered. But when new path is also in /tmp, that will work.

    Im using Ubuntu, home is in different partition. Any fix?

    Thanks