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
js fs-extra move() Function. The move() function moves a file or a directory from source to the destination specified by the user.
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.
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With