Request not ending in node.js (used to work) - node.js

I have this piece of code:
var app = require('http').createServer(function(req, res){
console.log(req);
req.addListener('end', function () {
fileServer.serve(req, res);
});
});
var statics = require('node-static');
var fileServer = new statics.Server('./');
app.listen(1344, '127.0.0.1');
app.on('error', function(err){
console.log(err);
})
It was working just fine, till I made a couple of changes, node gives an error, and when I went back, that error wasn't there anymore, but instead of work like it was working before the end event is not being fired. So, anything inside req.addListener('end', function (){});is not called.
And even if I run another node.js that uses the same event, is not being fired either. So is like if the end event of the request is broken. But how can that be possible?
Is not the first time it happens. Last time I ended up re-installing node (after try lots of different things). I would prefer to find a solution, so I can understand the problem!
NOTE: The original code include socket.io and other kind of connections, but I've just pasted the piece of code were the app is stuck on.
It could also be useful to know how to debug the problem!

#InspiredJW should get credit for pointing this out, since I had forgotten about it, but undoubtedly your problem is because of the changes in the readable streams. In order for the end event to get called you either have to attach a listener to the data event, or you have to call stream.resume().
require('http').createServer(function(req, res){
req.addListener('end', function () {
// won't ever get called in node v0.10.3
});
});
require('http').createServer(function(req, res){
req.addListener('end', function () {
// will get called in node v0.10.3 because we called req.resume()
});
req.resume();
});
require('http').createServer(function(req, res){
req.on('data', function (chunk) { });
req.addListener('end', function () {
// also will get called because we attached a data event listener
});
});
http://nodejs.org/api/stream.html#stream_compatibility

Related

Forked process in expressjs causes server to restart

I have an expressjs server and it uses a fork inside a route to make sure that the main loop isn't blocked (it's somewhat computing intensive). Every time this route is called, the server restarts. I've debugged this problem and found that the forking is what causes this behaviour but I don't understand why. The route is defined as follows:
module.exports = async function someComputingIntensiveFunction(req, res) {
try {
// some stuff
const childProcess = fork('../path/to/file.js');
childProcess.on('message', (data) => {
res.status(201).json(data).end();
});
catch (error) {
res.status(500).end()
}
}
Inside this file is
process.on('message', (data) => {
// do some stuff with data
// based on whatever the result is
process.send(result);
process.exit(result.status);
});
Am I forgetting a crucial part of forking which causes the expressjs server to restart? Thanks in advance for any help.

How to use socket.io to partially refresh page after server side code runs

I am trying to use socket.io to perform a simple operation in my solution built using nodejs (express). The objective is to ask the user to upload a file, and when the upload operation completes, display the message "file uploaded" on the screen without refreshing the page. To do this, I am using the following code:
Server side:
app.post('/fileupload', function(req, res) {
// Upload file stuff here...
mv(oldpath, newpath, function(err) {
if (err) throw err;
io.on('connection', function(socket) {
console.log('sock connected');
socket.emit('uploaded', {msg: 'File ' + files.filetoupload.name + 'uploaded to server'});
});
console.log('moved file');
res.sendFile(index);
});
});
});
And Client side:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('uploaded', function (data) {
console.log(data);
$('#messagebox').html(data.msg);
});
</script>
where messagebox is the originally empty div in which I want to display the message.
This code doesn't work. The io.on('connection'... code never gets called. I did move this code outside the app route with only a console.log statement to test that it works and it did. My assumption is that I am using the wrong event ('connection') here. But I cannot find anything in the documentation that allows me to create a socket object using a custom event. Can someone help me out?
If there is another way to implement a server code driven partial refresh of the client page (i.e. not using socket), I am open to learning that too. Thanks.
Interestingly, I figured it out shortly after posting this question (even though I had been trying for days before this).
Basically, I needed to create a socket object once (outside of all routes), and then use that object to create custom events within routes. So my working server side code (with no changes on client) now looks like this.
var socket = io.on('connection', function(socket) {
return socket;
});
app.post('/fileupload', function(req, res) {
//upload file stuff here
mv(oldpath, newpath, function(err) {
if (err) throw err;
socket.emit('uploaded', {msg : 'File ' + files.filetoupload.name + ' uploaded to server'});
});
});
});

Node.js on('end') stream's listener fires twice

It's a ordinary node practice, the on("end") callback fires twice per request even with using readable.once("end"). Here's tha code:
require("http").createServer(function (req, res) {
var readable = require("fs").createReadStream("./image.jpg",{highWaterMark:1024*1024});
readable.on("data", function (data) {
res.write(data);
})
readable.on("end", function () {
res.end()
console.log("Ended");
})
}).listen(9000, function () {
console.log("Listening.... on 9000");
});
There are 2 requests being sent whenever you request the page one for the main directory " / " and the other for the "favicon.ico" , so that why the function fires twice, in order to solve that put an if condition for the req.url and spacify the directory you want and it will work.

Multiple parllel request not processing in node js in async

var express=require('express');
var app=express();
module.exports=app;
app.get('/request1', function(req,res){
request1(function(){
res.end();
});
console.log("req1");
});
app.get('/request2',function(req,res){
console.log("req2");
request2(function(){
res.end();
});
});
function request1(callback){
process.nextTick(function(){
for(var i=0;i<9999999;i++){
console.log(i);
}
return callback();
});
};
function request2(callback){
process.nextTick(function(){
console.log('request2');
callback();
});
};
app.listen(3000);
In this code, I first call /request1 that takes time to process the loop.
But in another tab, I requested /request2 until /request1 is not complete. /request2 is also not executing.
Please help me how to solve this.
Node.js is single threaded. It peforms IO and Network Operations in async manner.
Here you are executing for loop which blocks the thread.
So once it will be finished, you will get the request of second request.
You should look in the concepts of callback , while making request. Its very important to use call back if you are really looking to do process which do some work at same time . How ever it is not possible to do multiple things at same time in node.js. Yet callback gives you a feel of that .

How to bind property to socket object using deployd?

I don't even know if that question makes sense. I don't have a lot of experience with socket.io or deployd. You'll probably understand what I'm trying to do from my code. It's similar to this. Here is my server code.
var deployd = require('deployd');
var options = {
//options go here
};
var dpd = deployd(options);
dpd.listen();
dpd.on('getLobby', function (lobby) {
dpd.lobby = lobby; //trying to bind variable to socket
console.log('get Lobby');
});
dpd.on('disconnect', function() {
console.log("disconnected");
});
dpd.on('connection', function (socket) {
console.log('connection');
});
and on my client side I have this
dpd.socket.emit('getLobby', lobby, function (data) {
console.log("emitted");
console.log(data);
});
The server works. My app works. Everything runs fine except for this code. I get no errors and no console logs. None of this code seems to work at all. It doesn't seem to emit and it doesn't seem to catch an emission if there even is one. I have tried lots of different ways of writing this.

Resources