res.writeHead and res.end in different scopes gives error - node.js

Below is my code:
const http = require('http');
const fs = require('fs');
http.createServer(testfunc)
.listen(3333);
function testfunc(req,res) {
if (req.method === 'GET'){
fs.readFile('index.html', function(err,data){
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.write("Hi");
});
res.end();
};
};
I am getting error as below when I send get request to /. Can you let me know what is the issue. If remove res.end() is working fine. But what's wrong in writing res.end().
events.js:292
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at write_ (_http_outgoing.js:629:17)
at ServerResponse.write (_http_outgoing.js:621:15)
at C:\Users\C5218529\3D Objects\RestApi\node-shop-sql\server.js:12:8
at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3) Emitted 'error' event on
ServerResponse instance at:
at writeAfterEndNT (_http_outgoing.js:684:7)
at processTicksAndRejections (internal/process/task_queues.js:85:21) { code:
'ERR_STREAM_WRITE_AFTER_END' }

res.end(); should be after res.write("Hi"); inside callback function fs.readFile().
Because callback function executes later (res.write) and res.end() is executing first.
We cannot write to response after we call res.end() statement.

fs.readFile('index.html', function(err,data){
// these callback statements will be executed later
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.write("Hi");
res.end();
});
// statements below will be executed immediately after fs.readFile as it is async

Related

node:_http_outgoing:862 issue in node js... fs not working

the terminal is showing >>>
node:_http_outgoing:862
throw new ERR_INVALID_ARG_TYPE(
^
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined
at new NodeError (node:internal/errors:399:5)
at write_ (node:_http_outgoing:862:11)
at ServerResponse.write (node:_http_outgoing:827:15)
at ReadFileContext.callback (c:\Users\me\Documents\Web Devolopment Challenge\intro\sample-server.js:7:9)
at FSReqCallback.readFileAfterOpen [as oncomplete] (node:fs:324:13) {
code: 'ERR_INVALID_ARG_TYPE'
}
Node.js v18.14.1
this is my code
var http = require('http')
var fs = require('fs')
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(7000);
and this is my html code
<html>
<h1>hello guys</h1>
<h2>heyy</h2>
</html>

getting error after opening port: Error [ERR_STREAM_WRITE_AFTER_END]: write after end (node.js)

I am learning node.js and want to open a server with a simple home, about, and error page. I (seem to have) followed the syntax exactly, but each time I load a request from the server in my browser, the page loads but I get an error in the vsCode terminal and the port closes. Here is my code:
const http = require('http')
const server = http.createServer((req, res)=>{
if(req.url ==='/'){
res.end('Home Page')
}
if(req.url ==='/about'){
res.end('about page')
}
res.end("error")
})
server.listen(5000, ()=>{
console.log("server is listening at port 5000...")
})
and here is the error I am getting:
server is listening at port 5000...
events.js:353
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at writeAfterEnd (_http_outgoing.js:694:15)
at ServerResponse.end (_http_outgoing.js:815:7)
at Server.<anonymous> (/home/nick/node-tutorial/app.js:11:5)
at Server.emit (events.js:376:20)
at parserOnIncoming (_http_server.js:896:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17)
Emitted 'error' event on ServerResponse instance at:
at writeAfterEndNT (_http_outgoing.js:753:7)
at processTicksAndRejections (internal/process/task_queues.js:83:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
You are calling res.end() twice from your request handler when you get either the / or /about requests. You can only call it once.
You end up calling res.end() more than once because when your request matches either / or /about, you call res.end() for those specific pages and then you have another res.end() at the end of the function that also executes.
To fix it, change to this:
const server = http.createServer((req, res)=>{
if (req.url ==='/') {
res.end('Home Page')
} else if (req.url ==='/about') {
res.end('about page')
} else {
res.statusCode = 404;
res.end("error")
}
});
Keep in mind that res.end() does not stop your function from continuing to execute. So, if you don't want to execute any more code in the function after calling res.end(), you need to either protect it with conditionals like I did above or add a return after you call res.end(...).
FYI, your specific error 'ERR_STREAM_WRITE_AFTER_END' is because res.end() writes out data to the stream and then closes the stream. So, the second time you try to call res.end(), it tries to write data to an already-closed stream which gives you the error you saw.

NodeJsApp - Unable to make successful http connections

I'm as new to Node and when I trying to run my first ever simple node app that makes an http connection to www.google.com host. While I tried some of the solutions suggested on prior threads nothing really seemed to help. While the below error is not a rare case but need someone to advise me what's missing from my setup/env.
source code - test.js - as simple as below -
var http = require('http');
var options = { host: 'www.google.com'};
http.get(options, function(err, res) {
console.log("GOT ERR?", err);
console.log("GOT RES?", res);});
I get the below error.
events.js:72
throw er; // Unhandled 'error' event
^
Error: getaddrinfo ENOTFOUND
at errnoException (dns.js:37:11)
at Object.onanswer [as oncomplete] (dns.js:124:16)
Your callback is wrong. Try to write your code as follow:
var http = require('http');
var options = { host: 'www.google.com'};
// notice that the callback only receives a res parameter
// errors are handled on an event below
var req = http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
});
// handle errors
req.on('error', function(e) {
console.log("Got error: " + e.message);
});
Here is the documentation for http.get: http://nodejs.org/api/http.html#http_http_get_options_callback
The error that you are seeing (throw er; // Unhandled 'error' event) is because you do not have an even handler for the error event. Notice the req.on('error') in my code to address this.

Nodejs - SPDY push on request error

I am having trouble launching my Node app. I get "TypeError: Cannot call method 'push' of undefined" error.
Here is my code:
spdy.createServer(credentials, app).listen(app.get('port'), function(req, res) {
res.push('public/js/bootstrap.min.js', {'content-type': 'application/javascript'}, function(err, stream) {
stream.end('alert("hello from push stream!")');
});
res.push('public/js/jquery.min.js', {'content-type': 'application/javascript'}, function(err, stream) {
stream.end();
});
res.push('public/css/bootstrap.min.css', {'content-type': 'text/css'}, function(err, stream) {
stream.end();
});
// write main response body and terminate stream
res.end('Hello World!');
console.log('Express HTTPS SPDY server listening on port ' + app.get('port'));
} );
I am running SDPY version 1.19.2 and NodeJS version 0.10.25.
Based on your comment, you are serving with HTTP/1.1. You need to be serving with HTTP2/SPDY for push to work.
Try this:
// set the root path of Express server
app.use(express.static(__dirname+'/public');
app.use(function(req, res) {
// your res.push code is here.
var stream = res.push('/js/bootstrap.min.js', {'content-type': 'application/javascript'});
stream.on('acknowledge', function() {
console.log('stream ACK');
});
stream.on('error', function() {
console.log('stream ERR');
});
stream.end('alert("stream SUCCESSFUL");');
res.end('<script src="/js/bootstrap.min.js"></script>');
});
spdy.createServer(credentials, app).listen(app.get('port'));
The callback function passed to listen() function takes no arguments. see line 49, file stream-test.js

error in node.js TypeError: Object #<Object> has no method 'createserver' at Object.<anonymous> (/home/aashish/chatbox/main.js:5:16)

i am facing some error in developing chat server client on linux please help
var http = require('http');
fs =require('fs');
var app = http.createserver(function (request, response)
{
enter code herefs.readfile("client.html",utf-8,function(error,data)
{
response.writehead(200,{'content-type': 'text/html'});
response.write(data);
response.end();
})
}).listen(1337);
io.sockets.on('connection',function(socket)
{
socket.on('message_to_server',function(data)
{
io.socket.emit("message_to_client",{message: data["message"]});
});
});
// at Object. (/home/aashish/chatbox/main.js:5:16)
error
it's createServer where S is an uppercase letter
createServer() is now deprecated meanwhile you could use Server() instead .. just check the following snippet or simply use express web framework.
var http = require("http");
var server = http.Server(function(request, response) {
response.end("heeloo world");
});
server.listen(3030, function(err){
if(!err)
console.log("success");
else
console.log("error");
});

Resources