Node stream get write after end error - javascript

I'm testing stream to upload and download files, below is my realy simple file download route that unzip my compressed file and send it via stream :
app.get('/file', (req, res) => {
fs.createReadStream('./upload/compress_aurelien-boquet.pdf')
.pipe(unzip)
.pipe(res);
});
I'm using express 4.15.2 btw.
When i try this route it works fine the first time and shows me the pdf on my browser, but if I refresh the page then my server get this error :
events.js:163
throw er; // Unhandled 'error' event
^
Error: write after end
at writeAfterEnd (_stream_writable.js:191:12)
at Unzip.Writable.write (_stream_writable.js:238:5)
at ReadStream.ondata (_stream_readable.js:557:20)
at emitOne (events.js:96:13)
at ReadStream.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
at ReadStream.Readable.push (_stream_readable.js:136:10)
at onread (fs.js:1938:12)
at FSReqWrap.wrapper [as oncomplete] (fs.js:629:17)
I would like to know what's going on ?

My bad, was using zlib library to gzip and unzip file but I forgot that "zlib.createGzip" and "zlib.createUnzip" return a stream so I was reusing an already ended stream causing me the 'write after end error'.
The bad thing I was doing :
const unzip = zlib.createUnzip();
app.get('/file', (req, res) => {
fs.createReadStream('./upload/compress_aurelien-boquet.pdf')
.pipe(unzip)
.pipe(res);
});
The good thing to do :
app.get('/file', (req, res) => {
fs.createReadStream('./upload/compress_aurelien-boquet.pdf')
.pipe(zlib.createGunzip())
.pipe(res);
});

Related

Why nodejs is not allowing me to access other route when I access the root route?

I am using the HTTP module of nodejs to create three routes('/','/about' and the last one treats any other route that is not defined as error route). When I access the root route first and try to access other route nodejs throw an error but when I access the error route or the about the route and try accessing another route it works fine.
Below are the code I wrote and the error nodejs throw
Error
PS C:\Users\Maxwell\Desktop\node> node app.js
node:events:368
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (node:internal/errors:371:5)
at ServerResponse.end (node:_http_outgoing:846:15)
at Server.<anonymous> (C:\Users\Maxwell\Desktop\node\app.js:10:9)
at Server.emit (node:events:390:28)
at parserOnIncoming (node:_http_server:951: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\Maxwell\Desktop\node> node app.js
node:events:368
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (node:internal/errors:371:5)
at ServerResponse.end (node:_http_outgoing:846:15)
at Server.<anonymous> (C:\Users\Maxwell\Desktop\node\app.js:10:9)
at Server.emit (node:events:390:28)
at parserOnIncoming (node:_http_server:951: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'
}
Code
const http = require('http');
const server = http.createServer((req,res)=>{
if(req.url==='/'){
res.end('Welcome Home Dev, You are loved');
}
if(req.url==='/about'){
res.end('This is the about page')
}
res.end(
`<h1>OOOp</h1>
<p>It seen like this page does not exit</p>
<a href='/'>back to homepage</a>
`
);
});
server.listen(5000);
Change to an if/else so you're only processing one branch of the if per request:
const server = http.createServer((req,res)=>{
if(req.url === '/'){
res.end('Welcome Home Dev, You are loved');
} else if (req.url === '/about') {
res.end('This is the about page')
} else {
res.end(
`<h1>OOOp</h1>
<p>It seen like this page does not exit</p>
<a href='/'>back to homepage</a>`);
}
});
Or, alternately, you could add a return after each res.send() to stop further execution in your request handler after you send a response. Remember, that just because you call res.send() your function still continues to execute so you need to manage control flow so the other code that sends a response doesn't execute once you've already sent a response.

Write after end error when launch server in nodejs

I am beginner at NodeJS and I'm doing a "NodeJS and Express.js full course" at freecodecamp yt and I copied author code which for him works perfectly, but I got an error.
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 us')
}
res.end('Error')
})
server.listen(3000, ()=>{
console.log('Server listening...');
})
I don't know why he got home, about and error page when user goes to the wrong page it should throw "Error" text on page, but instead my program is throwing an error in nodeJS program:
events.js:377
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (internal/errors.js:322:7)
at writeAfterEnd (_http_outgoing.js:694:15)
at ServerResponse.end (_http_outgoing.js:815:7)
at Server.<anonymous> (C:\Users\jonat\Desktop\nodejs\app.js:10:5)
at Server.emit (events.js:400:28)
at parserOnIncoming (_http_server.js:900:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:127: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'
}
Can someone explain this to me? I would be appreciate. Thank you in advance.
That’s caused by the res.end('Error'), which gets always executed. Try to put it into an else clause, or put a return before each res.end(…)

node-transmission package not working

I tried installing this package : https://github.com/FLYBYME/node-transmission in my local nodejs installation but I am getting following error while running example.js from the above github repository.
Error: connect ECONNREFUSED 127.0.0.1:9091
at Object.exports._errnoException (util.js:1022:11)
at exports._exceptionWithHostPort (util.js:1045:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 9091
After a bit research I tried to run a server at port 9091 using this code(in a separate server.js file)
const http = require('http')
const port = 9091
const requestHandler = (request, response) => {
console.log(request.url)
response.end('Hello Node.js Server!')
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
After running a server on port 9091, I started getting this error with example.js :
SyntaxError: Unexpected token H in JSON at position 0
at JSON.parse (<anonymous>)
at IncomingMessage.onEnd (F:NodeJS\node-transmission-master\lib\transmission.js:453:33)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
What must be causing this? I have no idea which step I have done wrong. That's why I described the whole process I followed.
I am very new to nodejs. Any help will be deeply appreciated.
The library is expecting a JSON formatted response and you are sending a simple text response. If you look through their source code you can see that their callServer function expects a stringified JSON but I can't see that in their docs.
You can change your code like so:
const http = require('http')
const port = 9091
const requestHandler = (request, response) => {
console.log(request.url)
// Format your response as a stringified JSON
response.end(JSON.stringify({message: 'Hello Node.js Server!'}));
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
In order to run the example from the node-transmission package, you need first to install and start the transmission-daemon.
The following steps are for Ubuntu:
Login as root or change to root with su - (be always careful what you do/install as root)
Install the transmission-daemon linux package: apt-get install transmission-daemon
Edit the daemon configuration for either disabling authentication or setting up your username/password (there is no default password). You can disable authentication by editing the relative flag in the configuration file:
pico /etc/transmission-daemon/settings.json
Set the auth flag to false: rpc-authentication-required:false
Press Ctrl-X then Y and then Enter to save the change
Start the daemon: start transmission-daemon
You should be able now to execute successfully the example.js and download its torrent link.

TypeError: res.writeHead is not a function chapter 6 Fullstack javascript development with MEAN

So I'm following along with the Full Stack Javascript development offered by Sitepoint and I've ran into a problem found within chapter 6. I've set up a basic http server which should allow incoming connections.
When I run index.js, I get a log to the console saying it is successfully running at my designated address(127.0.0.1:1337)
As soon as I try to go to that address in my browser it fails to connect and I get this error in my terminal
TypeError: Cannot read property 'toUpperCase' of undefined
at Server.<anonymous> (/Users/user/Documents/Git projects/human-resources/index.js:8:26)
at emitTwo (events.js:106:13)
at Server.emit (events.js:191:7)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:543:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:105:23)
It obviously has a problem with this line
req.method = req.method.toUpperCase();
But I don't know why, I thought maybe if I comment it out it'll work, but when I do that I get a similar error to the above but this time says res.writeHead is not a function
TypeError: res.writeHead is not a function
at Server.<anonymous> (/Users/user/Documents/Git projects/human-resources/index.js:12:9)
at emitTwo (events.js:106:13)
at Server.emit (events.js:191:7)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:543:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:105:23)
If anyone could offer some insight into where I or my code is going wrong that would be great my full code is listed below..
var http = require('http');
http.createServer(function (res,req) {
//A parsed url to work with in case there are parameters
var _url;
//In case the client uses lower case for methods
req.method = req.method.toUpperCase();
console.log(req.method + ' ' + req.url);
if (req.method !== 'GET') {
res.writeHead(501, {
'Content-Type': 'text/plain'
});
return res.end(req.method + ' is not implemented by this server');
}
if (_url = /^\/employees$/i.exec(req.url)) {
//return a list of employees
res.writeHead(200);
return res.end('employee list');
} else if (_url = /^\/employees\/(\d+)$/i.exec(req.url)) {
//find employee by id in the route
res.writeHead(200);
return res.end('a single employee');
} else {
//try to send the static file
res.writeHead(200);
return res.end('static file maybe');
}
}).listen(1337, '127.0.0.1');
console.log('Sever Running at http://127.0.0.1:1337/');
I have used the request and response in the http.createServer() in the wrong order, I used response then request, should be request and then response like so;
http.createServer(function (req,res) {

Troubleshooting Error: connect ECONNREFUSED in nodejs stream-adventure tutorial

I've been working through the learnyoujs and stream-adventure tutorials:
https://github.com/substack/stream-adventure
https://github.com/rvagg/learnyounode#learn-you-the-nodejs-for-much-win
I've gotten all the way through the first set and most of the way thorough the second, but I keep getting an odd error... usually I can get it to go away.
Here's the command/error:
DEV/javascript/streamAdventure » stream-adventure run httpserver.js
stream.js:94
throw er; // Unhandled stream error in pipe.
^
Error: connect ECONNREFUSED
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)
This will launch but not kill the process for node, so I ps aux | grep node and then find the process and kill it.
Here's the "working" code from the tutorial:
var http = require('http');
var through = require('through');
var server = http.createServer(function (req, res) {
if (req.method === 'POST') {
req.pipe(through(function (buf) {
this.queue(buf.toString().toUpperCase());
})).pipe(res);
}
else res.end('send me a POST\n');
});
server.listen(8000);
If I just run nod httpserver.js and then curl at it, it works fine.... so does anyone have any insight into what is causing this error?
There is a pull request to fix this, here:
https://github.com/substack/stream-adventure/pull/16
Try to listen on port 8001 instead and rerun verify after closing all processes listening on 8000.
I had the same error, problem wasn't with though node however, it was with mysql.
Ran "mysqld_safe restart" (depends on your version), then it worked fine.

Categories