2013-07-15 18 views
9

sto cercando di spostare file caricato da /tmp a home directory utilizzando NodeJS/ExpressJS:spostare il file in ExpressJS/NodeJS

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

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

Ma non funzionava e nessun errore incontrato. Ma quando il nuovo percorso è anche in /tmp, funzionerà.

Im utilizzando Ubuntu, home è in partizione diversa. Qualche correzione?

Grazie

risposta

18

Sì, fs.rename non si muove di file tra due diversi dischi/partizioni. Questo è il comportamento corretto. fs.rename fornisce identiche funzionalità a rename(2) in linux.

Leggere il problema correlato pubblicato here.

per ottenere ciò che si vuole, si dovrebbe fare qualcosa di simile:

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

Un altro modo è quello di utilizzare fs.writeFile. fs.unlink in callback rimuoverà il file temporaneo dalla directory 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

cosa sono ** dati ** in questo? e come posso ottenerlo dall'oggetto richiesta? – Vishal

0

Questo esempio tratto da:

Una funzione Node.js in Action mossa() che rinomina, se possibile, o ricade copiando

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

soluzione ES6 aggiornato pronta all'uso con promesse e async/attendi:

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