2013-02-01 15 views
7

Il mio problema è che non posso essere sicuro di quando un file è stato scritto correttamente e il file è stato chiuso. Si consideri il seguente caso:Come svuotare correttamente il file Node.js writeStream?

var fs = require('fs'); 
var outs = fs.createWriteStream('/tmp/file.txt'); 
var ins = <some input stream> 

... 
ins.on('data', function(chunk) { out.write(chunk); }); 
... 
ins.on('end', function() { 
    outs.end(); 
    outs.destroySoon(); 
    fs.stat('/tmp/file.txt', function(err, info) { 

     // PROBLEM: Here info.size will not match the actual number of bytes. 
     // However if I wait for a few seconds and then call fs.stat the file has been flushed. 
    }); 
}); 

Allora, come faccio a forzare o comunque assicurarsi che il file è stato correttamente lavata prima di accedervi? Devo essere sicuro che il file sia presente e completo, poiché il mio codice deve generare un processo esterno per leggere ed elaborare il file.

risposta

7

fare post-elaborazione del file in caso writeable stream'sclose:

outs.on('close', function() { 
    <<spawn your process>> 
}); 

Inoltre, non c'è bisogno per il destroySoon dopo il end, sono one and the same.

+0

Grazie, l'ascolto dell'evento "vicino" sembra fare il trucco. Non sapevo che destroySoon era ridondante per i file. –

+0

Grande. Sono contento di poterti aiutare. –

+5

questo in realtà non funziona per noi. Abbiamo ancora alcuni casi (su SmartOS/Mac e Windows in cui viene emessa la chiusura PRIMA che il contenuto del file sia stato svuotato) – mgoetzke