-1

I've node app with function that inside call to to other two function,I want to use some async behavior for it,what is recommended to use in this case. example will be very helpful.

function myFunction(req,res){

//from here this is the first place which I want to use warp in function

var dataChunks = [],
                dataRaw,
                data;

                req.on("data", function (chunk) {
                    dataChunks.push(chunk);
                });

                req.on("end", function () {
                    dataRaw = Buffer.concat(dataChunks);
                    data = dataRaw.toString();
                    console.log(data);

//here is the second code which I want to warp in function and call after the first function

 var filePath = 'C://test.txt';
                var writeStream = fs.createWriteStream(filePath, {flags: 'w'});
                writeStream.write(data);
                res.status(200).send('ok');

            })

}

one more thing,as I saw until now async is how the node framework working and to add additional libarary like Q is not overkill?

  • 1
    You will need to describe what problem you're trying to solve with the code you have. **Yes**, it is recommended to use Promises for managing async code in node.js. You may use the Promise support built into node.js or you may pick a third party library like Q or Bluebird (my favorite is Bluebird). That is your choice. There is no right or wrong answer there, it depends upon what you like, what features you think are important, etc... Adding a library to help you manage async code is not overkill. This is a server process - you don't need to minimize libraries used. – jfriend00 Jun 23 '15 at 06:50
  • @jfriend00-Thanks!the code is doing two things which are diffrent 1 .get data from the request body and 2. to write it (req body data) to a file, how would you recomended to do it? please provide example since Im new to asyhc stuff.... –  Jun 23 '15 at 07:00
  • @JhonDree It looks like you want streams, not promises. – thefourtheye Jun 23 '15 at 07:08
  • @thefourtheye- Thanks, why streams ? can you provide example please? –  Jun 23 '15 at 07:11

1 Answers1

1

I don't even see why you particularly need promises for this.

function myHandler(req, res) {
    var dataChunks = [],
        dataRaw,
        data;

    req.on("data", function (chunk) {
        dataChunks.push(chunk);
    });

    req.on("end", function () {
        dataRaw = Buffer.concat(dataChunks);
        data = dataRaw.toString();
        console.log(data);
        var filePath = 'C://test.txt';
        var writeStream = fs.createWriteStream(filePath, {flags: 'w'});
        writeStream.write(data);
        writeStream.on('finish', function() {
            res.status(200).send('ok');
        });
        writeStream.end();
    });
}      

Or, you could probably pipe the incoming stream right into your file stream and write even less code.

function myHandler(req, res) {
    var filePath = 'C://test.txt';
    var writeStream = fs.createWriteStream(filePath, {flags: 'w'});
    req.pipe(writeStream);
    req.on("end", function() {
        res.status(200).send('ok');
    });
}        
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Thanks a lot !!!Voted up!can I use the second option which is working 1. can you please explain why you use stream instead of async ? 2. do I need to use some error handling for this and how ? –  Jun 23 '15 at 07:31
  • @JhonDree - `req` is a stream already. You were already using a stream for the destination. `.pipe()` is a natural to write one incoming stream to a destination stream. Yes, you would probably want some error handling on the write stream. You can listen to the `error` event. – jfriend00 Jun 23 '15 at 07:32
  • Thanks one more issue when I use the second code which is working I got this error :TypeError: undefined is not a function at IncomingMessage. (c:\Users\i056926\WebstormProjects\ReverseProxyApp\server.js:50:25) at IncomingMessage.emit (events.js:129:20) at _stream_readable.js:908:16 at process._tickCallback (node.js:355:11) any idea why? –  Jun 23 '15 at 07:38
  • I got it in res.status(200).send('ok'); which is surprising –  Jun 23 '15 at 07:43
  • Probably the `res` argument to the myHandler function is not actually an http response object or you mistyped and are using `req` where my code shows `res`. – jfriend00 Jun 23 '15 at 07:57