11

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

4 Answers 4

20

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 */ });
Sign up to request clarification or add additional context in comments.

Comments

11

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

2 Comments

what is data in this? and how can i get it from the request object?
what will be the new path?
4

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.