Move File in ExpressJS/NodeJS

2019-02-12 18:17发布

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条回答
趁早两清
2楼-- · 2019-02-12 19:03

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 */ });
查看更多
劳资没心,怎么记你
3楼-- · 2019-02-12 19:14

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);
    });
}
查看更多
我只想做你的唯一
4楼-- · 2019-02-12 19:17

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);
}
}
查看更多
时光不老,我们不散
5楼-- · 2019-02-12 19:22

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);
        });
    }); 
}); 
查看更多
登录 后发表回答