0

Referring to slide no 35 in ppt on slideshare

When I run this code

var server = my_http.createServer();  

server.on("request", function(request,response){
var chunks = [];  
output     = fs.createWriteStream("./output");

request.on("data",function(chunk){

   chunks = forEachLine(chunks.concat(chunk),function(line){

      output.write(parseInt(line,10)*2);
      output.write("\n");

   })
});


request.on("end",function(){
   response.writeHeader(200,{"Content-Type":"plain/text"})
   response.end("OK\n");
   output.end()
   server.close()
})


});

server.listen("8080");

I get error as

 chunks = forEachLine(chunks.concat(chunk),function(line){
            ^
ReferenceError: forEachLine is not defined

Of course I unserstand that I need to include some library but when I googled this I found nothing . Since I am complete newbie to this I have absolutely no idea how to resolve it.

Any suggestions will be appreciable.

EDIT

Using the suggested answer I am getting error as

    events.js:72
        throw er; // Unhandled 'error' event
              ^
TypeError: Invalid non-string/buffer chunk
    at validChunk (_stream_writable.js:150:14)
    at WriteStream.Writable.write (_stream_writable.js:179:12)
    at /var/www/html/experimentation/nodejs/first.js:18:20
    at Array.forEach (native)
    at forEachLine (/var/www/html/experimentation/nodejs/first.js:8:60)
    at IncomingMessage.<anonymous> (/var/www/html/experimentation/nodejs/first.js:17:18)
    at IncomingMessage.EventEmitter.emit (events.js:95:17)
    at IncomingMessage.<anonymous> (_stream_readable.js:736:14)
    at IncomingMessage.EventEmitter.emit (events.js:92:17)
    at emitReadable_ (_stream_readable.js:408:10)

Thanks

alwaysLearn
  • 6,882
  • 7
  • 39
  • 67
  • How about replacing `forEachLine(chunks.concat(chunk),function(line){` with `chunks.concat(chunk).forEach(function(line){`? – Dogbert Jul 02 '13 at 10:29
  • @Dogbert Replaced but it now gives error ` ^ TypeError: Invalid non-string/buffer chunk at validChunk (_stream_writable.js:150:14) at WriteStream.Writable.write (_stream_writable.js:179:12) at **** at Array.forEach (native) ... ` – alwaysLearn Jul 02 '13 at 10:33

1 Answers1

0

See proxy_stream.js

function forEachLine(chunks, callback) {
    var buffer = chunks.join("")
    buffer.substr(0, buffer.lastIndexOf("\n")).split("\n").forEach(callback)
    return buffer.substr(buffer.lastIndexOf("\n") + 1).split("\n")
}

The link to the repo was on the first slide.

EDIT BY LET's CODE FOR ERROR MESSAGE

Came to know the actual issue now .

I was using nod v0.10 and it is buggy in getting the streams so I was getting the error. Downgraded to v0.8 and same code is working perfect .

alwaysLearn
  • 6,882
  • 7
  • 39
  • 67
mak
  • 13,267
  • 5
  • 41
  • 47