11

我正在尝试使用 NodeJS/ExpressJS 将上传的文件从目录/tmp移动:home

fs.rename('/tmp/xxxxx', '/home/user/xxxxx', function(err){
    if (err) res.json(err);

console.log('done renaming');
});

但它不起作用,也没有遇到错误。但是,当新路径也在 中时/tmp,这将起作用。

我使用的是 Ubuntu,home在不同的分区中。有什么修复吗?

谢谢

4

4 回答 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 */ });
于 2013-07-15T12:17:22.190 回答
11

另一种方法是使用fs.writeFile. fs.unlinkin callback 将从 tmp 目录中删除临时文件。

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);
        });
    }); 
}); 
于 2014-01-29T12:59:47.397 回答
2

更新的 ES6 解决方案准备好与 promises 和 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);
    });
}
于 2017-05-23T10:18:27.013 回答
1

此示例取自:Node.js in Action

一个 move() 函数,如果可能的话,重命名,或者回退到复制

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);
}
}
于 2015-03-17T17:10:47.497 回答