Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move File in ExpressJS/NodeJS

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

like image 505
JR Galia Avatar asked Jul 15 '13 08:07

JR Galia


People also ask

How do I move files in node JS?

js fs-extra move() Function. The move() function moves a file or a directory from source to the destination specified by the user.

How do I move a file to a directory in node JS?

To move a file from a directory to another in Node. js, you can use the fs. rename(oldPath, newPath, callback) method. Here is a moveFile() function that can be used to move a file to other directory.

How do I move a file in Javascript?

The MoveFile() method is used to move a file from a source to a destination. This method takes two parameters. The first parameter, source, is the location of the file to be moved, while the second parameter, destination, is the new location of the moved file.


1 Answers

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);
}
}
like image 146
Teoman shipahi Avatar answered Oct 21 '22 19:10

Teoman shipahi