Node.js "write after end" error
Return your body in response.end()
instead of response.write()
function start (response) {
console.log("Request handler 'start' was called.");
var body = '<html>'+
'<head>'+
'<meta http-equiv="Content-Type" content="text/html; '+
'charset=UTF-8" />'+
'</head>'+
'<body>'+
'<div>Hello Start</div>' +
'</body>'+
'</html>';
response.writeHead(200, {"Content-Type": "text/html"});
response.end(body);
}
Edit 1:
The first time response.write()
is called, it will send the buffered header information and the first body to the client. The second time response.write()
is called, Node.js assumes you're going to be streaming data, and sends that separately. That is, the response is buffered up to the first chunk of body.
So, if you want to send only one chunk, you must use response.end(body)
, and if you want to send multiple chunks you must end you called with the response.end()
after multiple response.write()
.
Example single chunk:
function (chunk){
response.end(chunk);
}
Example multiple chunks:
function (chunkArray){
// loop on chunks
for(var i=0; i < chunkArray.length; i++){
response.write(chunkArray[i]);
}
// end the response with empty params
response.end();
}