Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting the end of a writeStream in Node

This is what I've got, and I keep getting an error because the file doesn't exist yet when I just do it sequentially.

How can I trigger an action upon the writeStream getting closed?

var fs = require('fs'), http = require('http');
http.createServer(function(req){
    req.pipe(fs.createWriteStream('file'));


    /* i need to read the file back, like this or something: 
        var fcontents = fs.readFileSync(file);
        doSomethinWith(fcontents);
    ... the problem is that the file hasn't been created yet.
    */

}).listen(1337, '127.0.0.1');
like image 885
user2958725 Avatar asked Nov 07 '13 06:11

user2958725


People also ask

What is readable stream in node JS?

There are four fundamental stream types in Node. js: Readable, Writable, Duplex, and Transform streams. A readable stream is an abstraction for a source from which data can be consumed. An example of that is the fs. createReadStream method.

Which object is a stream in node JS?

There are four main types of streams in Node. js; readable, writable, duplex and transform. Each stream is an eventEmitter instance that emits different events at several intervals.

What is a readable stream?

A readable stream lets you read data from a source. The source can be anything. It can be a simple file on your file system, a buffer in memory or even another stream. As streams are EventEmitters , they emit several events at various points. We will use these events to work with the streams.


1 Answers

Writable streams have a finish event that is emitted when the data is flushed.

Try the following;

var fs = require('fs'), http = require('http');

http.createServer(function(req, res){
    var f = fs.createWriteStream('file');

    f.on('finish', function() {
        // do stuff
        res.writeHead(200);
        res.end('done');
    });

    req.pipe(f);
}).listen(1337, '127.0.0.1');

Though I wouldnt re-read the file. You can use through to create a stream processor.

like image 193
Bulkan Avatar answered Oct 21 '22 19:10

Bulkan