简体   繁体   中英

alternative to through2-map in node.js [related to learnyounode]

Problem i am solving:

Write an HTTP server that receives only POST requests and converts incoming POST body characters to upper-case and returns it to the client.

Your server should listen on the port provided by the first argument to your program.

My Solution

var http = require('http');
var map = require('through2-map')


http.createServer(function(request,response){

    if (request.method == 'POST'){
    request.pipe(map(function (chunk) {
      return chunk.toString().toUpperCase();
    })).pipe(response);



    }

}).listen(process.argv[2]);

Can i implement is without using through2-map ?
My crippling solution which doesn't work:

 request.on('data',function(data){
     body += data.toString();
     console.log(body);
 });
 request.pipe(body.toUpperCase()).pipe(response);

Can i do the real hard way ?

In the 2nd snippet, body.toUpperCase() will act immediately before any of the 'data' events have actually occurred. The call to .on() only adds the event handler so it will be called, but doesn't yet call it.

You can use the 'end' event , along with 'data' , to wait for all data chunks to be received, ready to be uppercased:

request.on('data', function (data) {
    body += data.toString();
});

request.on('end', function () {
    response.end(body.toUpperCase());
});

Note: Be sure that body is being declared and assigned an initial value:

var body = '';

response.on('data', ...);

// ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM