2013-07-15 25 views
9

Tôi đang cố gắng để di chuyển tập tin được tải lên từ /tmp để home thư mục sử dụng NodeJS/ExpressJS:Move File trong ExpressJS/NodeJS

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

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

Nhưng nó đã không làm việc và không có lỗi gặp phải. Nhưng khi đường dẫn mới cũng nằm trong /tmp, đường dẫn đó sẽ hoạt động.

Im sử dụng Ubuntu, home nằm trong phân vùng khác. Mọi sửa chữa?

Cảm ơn

Trả lời

18

Có, fs.rename không di chuyển tệp giữa hai đĩa/phân vùng khác nhau. Đây là hành vi chính xác. fs.rename cung cấp chức năng giống hệt nhau cho rename(2) trong linux.

Đọc sự cố liên quan được đăng here.

Để có được những gì bạn muốn, bạn sẽ phải làm một cái gì đó như thế này:

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 */ }); 
10

Một cách khác là sử dụng fs.writeFile. fs.unlink trong gọi lại sẽ xóa tệp tạm thời khỏi thư mục 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); 
     }); 
    }); 
}); 
+0

** dữ liệu ** là gì? và làm thế nào tôi có thể lấy nó từ đối tượng yêu cầu? – Vishal

0

Ví dụ này lấy từ: Node.js in Action

Một chức năng di chuyển() mà đổi tên, nếu có thể, hoặc rơi trở lại để sao chép

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

Cập nhật ES6 giải pháp sẵn sàng để sử dụng với lời hứa và không đồng bộ/chờ đợi:

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