localhost not responding for nodejs project [duplicate] - node.js

This question already has answers here:
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
(5 answers)
Closed 5 months ago.
I am new to nodejs and still learning so please help me out here.
const http=require('http')
const server=http.createServer((req,res)=>{
if(req.url==='/'){
res.end('Welcome to our home page')
}
if(req.url==='/about'){
res.end("Here is our short abt page")
}
res.end(`
<h1>OOps!</h1>
<p>We can't seem to find the page you are looking for</p>
<a href='/'>Go back home</a>
`)
})
server.listen(2000)
The above mentioned code gives the following error:
node:events:505
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (node:internal/errors:372:5)
at ServerResponse.end (node:_http_outgoing:846:15)
at Server.<anonymous> (c:\Users\Hp\Desktop\node\app.js:10:9)
at Server.emit (node:events:527:28)
at parserOnIncoming (node:_http_server:956:12)
at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
Emitted 'error' event on ServerResponse instance at:
at emitErrorNt (node:_http_outgoing:726:9)
at processTicksAndRejections (node:internal/process/task_queues:84:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
PS C:\Users\Hp\Desktop\node> node "c:\Users\Hp\Desktop\node\app.js"
node:events:505
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (node:internal/errors:372:5)
at ServerResponse.end (node:_http_outgoing:846:15)
at Server.<anonymous> (c:\Users\Hp\Desktop\node\app.js:10:9)
at Server.emit (node:events:527:28)
at parserOnIncoming (node:_http_server:956:12)
at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
Emitted 'error' event on ServerResponse instance at:
at emitErrorNt (node:_http_outgoing:726:9)
at processTicksAndRejections (node:internal/process/task_queues:84:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
The page at localhost:2000 works at times for the main page (mostly) but gives the "site can't be reached" error for the rest. Do I need to start the xampp apache?

Here we should observe the code execution clearly.
When we visit localhost:2000, First mentioned if condition will be executed and send the response as Welcome to our home page
if(req.url==='/'){
res.end('Welcome to our home page')
}
Then after it tries to check the second if condition and as the if condition is false that block of code will not be executed
if(req.url==='/about'){
res.end("Here is our short abt page")
}
Then it tries to execute the last block of code
res.end(`
<h1>OOps!</h1>
<p>We can't seem to find the page you are looking for</p>
<a href='/'>Go back home</a>
`)
As the res is already sent with first block of if condition, Now again these last lines of code will try to send the response, which will result in an error and the app will be crashed. Because the response is already ended its process.
To overcome these issues, try to change the code in the below-mentioned way.
const server=http.createServer((req,res)=>{
if(req.url==='/'){
res.end('Welcome to our home page')
return
}
if(req.url==='/about'){
res.end("Here is our short abt page")
return;
}
res.end(`
<h1>OOps!</h1>
<p>We can't seem to find the page you are looking for</p>
<a href='/'>Go back home</a>
`)
})
The above-mentioned code snippet will work fine and fixes the issue.

Related

promise reject crash try catch everywhere

I put try catch everywhere in my code, but this error still crashes the app. What is the problem:
node:events:515
throw er; // Unhandled 'error' event
^
AbortError: The operation was aborted
at Fetch.onAborted (node:internal/deps/undici/undici:6241:53)
at Fetch.emit (node:events:537:28)
at Fetch.abort (node:internal/deps/undici/undici:5511:14)
at requestObject.signal.addEventListener.once (node:internal/deps/undici/und
ici:5542:22)
at [nodejs.internal.kHybridDispatch] (node:internal/event_target:645:20)
at AbortSignal.dispatchEvent (node:internal/event_target:587:26)
at abortSignal (node:internal/abort_controller:292:10)
at AbortController.abort (node:internal/abort_controller:322:5)
at AbortSignal.abort (node:internal/deps/undici/undici:4974:36)
at [nodejs.internal.kHybridDispatch] (node:internal/event_target:645:20)
at [nodejs.internal.kHybridDispatch] (node:internal/event_target:645:20)
at AbortSignal.dispatchEvent (node:internal/event_target:587:26)
at abortSignal (node:internal/abort_controller:292:10)
at AbortController.abort (node:internal/abort_controller:322:5)
at abort (/home/eguneys/chess/rhx/lib/stream.js:17:24)
at PlayOnTurn.fAbort (/home/eguneys/chess/openex/lib/play.js:59:21)
at PlayOnTurn.respondGameAbort (/home/eguneys/chess/openex/lib/play.js:27:68
)
Emitted 'error' event on Readable instance at:
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:2
1) {
code: 'ABORT_ERR'
}

Why am I getting "unexpected end of file" with zlib.js?

I'm using the unzipper Node.js package and it was working fine, processing through my files, when suddenly for seemingly no reason, I got this error:
events.js:291
throw er; // Unhandled 'error' event
^
Error: unexpected end of file
at Zlib.zlibOnError [as onerror] (zlib.js:180:17)
Emitted 'error' event on Parse instance at:
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
errno: -5,
code: 'Z_BUF_ERROR'
}
The error gets thrown every time this particular file is processed, others seem to work fine, but I can't think of what's different about this one.
Is this potentially a user-mistake, or a bug I should report?
code:
console.log("unzipping", zipPath) // <-- error triggers after this log
fs.createReadStream(zipPath)
.pipe(unzipper.Parse())
.on('entry', function(entry) {
entry.pipe(fs.createWriteStream(csvPath)).on('finish', () => {
console.log("done unzipping", zipPath)
fd = fs.openSync(csvPath, "r+")
initializeFile()
})
})
}

NodeJS : Error: read ECONNRESET at TCP.onStreamRead (internal/stream_base_commons.js:111:27)

Using Polling like below to check if the content of the file is changed then, other two functions are called
var poll_max_date=AsyncPolling(function (end,err) { if(err) {
console.error(err); } var stmp_node_id=fs.readFileSync(path.join(__dirname,'node_id'),"utf8");
console.log("--------loaded node : "+stmp_node_id);
if(druid_stmp_node_id!=stmp_node_id) {
// MAX DATA CUT-OFF DRUID QUERY
druid_exe.max_date_query_fire();
// // DRUID QUERY FOR GLOBAL DATA
druid_exe.global_druid_query_fire();
druid_stmp_node_id=stmp_node_id; }
end(); }, 1800000).run();//30 mins
Its working fine for sometime, but then getting below error like after 4 - 5hours :
events.js:167
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27) Emitted 'error' event at:
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
tried using fs.watch to monitor the changes in the file instead of polling like below :
let md5Previous = null; let fsWait = false;
fs.watch(dataSourceLogFile, (event, filename) => { if (filename) {
if (fsWait) return;
fsWait = setTimeout(() => {
fsWait = false;
}, 1000);
const md5Current = md5(fs.readFileSync(dataSourceLogFile));
if (md5Current === md5Previous) {
return;
}
md5Previous = md5Current;
console.log(`${filename} file Changed`);
// MAX DATA CUT-OFF DRUID QUERY
druid_exe.max_date_query_fire();
// DRUID QUERY FOR GLOBAL DATA
druid_exe.global_druid_query_fire(); } });
Its is also working fine for sometime, but then getting same error like after 4 - 5hours :
events.js:167 throw er; // Unhandled 'error' event ^
Error: read ECONNRESET at TCP.onStreamRead
(internal/stream_base_commons.js:111:27) Emitted 'error' event at: at
emitErrorNT (internal/streams/destroy.js:82:8) at emitErrorAndCloseNT
(internal/streams/destroy.js:50:3)
But when run in Local Machine, its working fine. the error occurs only when run in remote Linux Machine.
somebody can help me how I can fix that problem?
Use fs.watchFile once , because fs.watch is not consistent across platforms,
https://nodejs.org/docs/latest/api/fs.html#fs_fs_watchfile_filename_options_listener
Change your code according to the requirement.
It has been happening since the users are closing the browser before the data request is received, leading to Connection Reset.
Used PM2 (http://pm2.keymetrics.io/) to run the application, and it is working great now .

Discord Bot crashed after some time

So I have a discord bot which works perfectly fine, but after some time (about 30 minutes) the bot crashes with this error message:
Error: Unhandled "error" event. ([object Object])
at Client.emit (events.js:186:19)
at WebSocketConnection.onError (C:\Users\Paul\Desktop\Hype-Bot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:374:17)
at WebSocket.onError (C:\Users\Paul\Desktop\Hype-Bot\node_modules\ws\lib\event-target.js:128:16)
at emitOne (events.js:116:13)
at WebSocket.emit (events.js:211:7)
at _receiver.cleanup (C:\Users\Paul\Desktop\Hype-Bot\node_modules\ws\lib\websocket.js:211:14)
at Receiver.cleanup (C:\Users\Paul\Desktop\Hype-Bot\node_modules\ws\lib\receiver.js:557:13)
at WebSocket.finalize (C:\Users\Paul\Desktop\Hype-Bot\node_modules\ws\lib\websocket.js:206:20)
at emitOne (events.js:116:13)
at TLSSocket.emit (events.js:211:7)
at emitErrorNT (internal/streams/destroy.js:64:8)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickDomainCallback (internal/process/next_tick.js:218:9)
Does someone know how to solve this?
I've been looking for someone who needs some help with this sort of thing, and lo and behold here you are. I too have run into this issue. You have a network error that happens when your bot sends something called a heartbeat to the servers to say to them: i am online. Then the server will send it back. If it is sent and there is not a message returned from the server then it will give you your error. All you have to do is go into the following path in your bot folder /node_modules/discord.js/src/client/websocket/WebSocketConnection.js
Then in that file go to a section that looks like this:
onError(error) {
if (error && error.message === 'uWs client connection error') {
this.reconnect();
return;
}
/**
* Emitted whenever the client's WebSocket encounters a connection error.
* #event Client#error
* #param {Error} error The encountered error
*/
this.client.emit(Constants.Events.ERROR, error);
}
and what I did is change it to this:
onError(error) {
if (error && error.message === 'uWs client connection error') {
this.reconnect();
return;
}
console.log("Attempting to reconnect!")
return this.reconnect()
/**
* Emitted whenever the client's WebSocket encounters a connection error.
* #event Client#error
* #param {Error} error The encountered error
*/
this.client.emit(Constants.Events.ERROR, error);
}
I hope this helps!
Wishing you luck,
Zaedus

ForEachLine() in node.js

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
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 .

Resources