nodejs hangs with express static files - node.js

The Problem:
If I comment out the express['static'] line, the code runs perfectly. If I include it (or change the order), the app hangs for a while before responding.
To Recreate:
Run the app, load up a browser and go to 127.0.0.1:51783
Refresh the page constantly (or use curl), the console will give you an output similar to:
GET / 1 ms
Then, when the timeout kicks in and the 15 requests are sent, the server becomes unresponsive and you get the following:
Server Now Unresponsive but requests queued
GET / 35549 ms
app.js
var http = require('http');
var express = require('express');
var app = express.createServer();
app.use(express.logger({ format: '\x1b[1m:method\x1b[0m \x1b[33m:url\x1b[0m :response-time ms' }));
app.use(express.bodyParser());
app.use(express['static'](__dirname + '/')); //Comment me and all works perfectly!
app.listen(51783);
http.globalAgent.maxSockets = 500; //doesn't help
setTimeout(function(){
console.log('Server Now Unresponsive but requests queued');
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15].forEach(function(item){
http.request({host:'http://cnn.com', port:80, path:'/null', method:'GET'}, function(res){
}).on('error', function(e){});
});
},5000);

There is something not quite right about that http request. I recommend using the request module for this sort of thing. Either way this works:
var http = require('http');
var express = require('express');
var app = express.createServer();
app.configure(function(){
app.use(express.logger({ format: '\x1b[1m:method\x1b[0m \x1b[33m:url\x1b[0m :response-time ms' }));
app.use(express.bodyParser());
app.use(express['static'](__dirname + '/public')); //Comment me and all works perfectly!
})
app.listen(51783);
var request = require('request');
setTimeout(function(){
console.log('Server Now Unresponsive but requests queued');
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15].forEach(function(item){
request('http://www.google.com', function (error, response, body) {
console.log("request number "+item+" received")
})
});
},5000);

Related

how to use post method in nodejs?

I am using post method in nodejs
Well it is working fine when I run it using postman
but when I run it in my browsers it shows error
Cannot GET /listUsers
and
listUsers:1 GET http://localhost:8081/listUsers 404 (Not Found)
this
here is my node js code
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.post('/listUsers', function (req, res) {
var f = parseInt(req.body.f);
console.log("hello" + f);
var l = parseInt(req.body.l);
var sum = Number(f + l);
res.send('The sum is: ' + Number(sum));
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
here is my jquery code from where I am sending data
usid();
function usid(med){
var f = "my new name";
$.ajax({
crossDomain: true,
url:"http://localhost:8081/listUsers",
method:"POST",
data:{med,f:f},
success:function(data,status){
console.log("send");
}
})
}
can I get where I am doing mistake?
You are not submitting any form/storing any resource. What you are trying should ideally be done with GET.
Reasons it is not working with browser:
Visiting a page by changing url is a GET method. You do not have a GET method defined in your app for this route. Only one POST method.
What you can do:
Change POST to GET both in server and your AJAX. Change both methods accordingly. You will then have to pass query params(google something and everything after the question mark is how query Params work).

Express server does not receive request, http module server does

I am making a HTTP server for a Biometric device. I cannot make changes to the devices firmware. I can just add the server ip.
So I first made an express server to receive requests, but it didnt receive any. Later I made a server using http module of Nodejs and voila it was able to do so.
The problem is writing a server for a very big application in http module would be difficult and there is very less support available for it. I'd prefer to user Express. Any Ideas why express is failing?
Edit:
So someone asked for code here they are:
http module
var http = require('http');
var port = 7005;
var s = http.createServer();
s.on('request', function(request, response) {
response.writeHead(200);
console.log(request.method);
console.log(request.headers);
console.log(request.data);
response.write('hi');
response.end();
});
s.listen(port);
console.log('Browse to http://127.0.0.1:' + port);
Express Server:
var express = require('express')
var app = express()
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
// respond with "hello world" when a GET request is made to the homepage
app.all('/', function (req, res) {
res.send('hello world')
console.log(req.method + " Request Aayi");
console.log(req.body);
});
app.listen(7005);

Creating web server with express (node.js)

js and am trying to create a web server and server side code for my web application.
I understand express is used to get access to all static files.
I am trying to start a simple server using express as follows:
var express = require("express");
var url = require("url");
var http = require("http");
var port = 3000;
var app = express();
app.use(express.static(__dirname + "/Client"));
http.createServer(app).listen(port, function(req,res){
console.log("Server running at: " + "http://" + port);
res.writeHead(200,{
"Content-Type":"text/plain"
});
});
I cant seem to do anything with my res variable in my callback, which I am trying to use as a response object. Allowing me to do things like:
res.end(¨hello world¨);
Is this callback even allowed, or how can I start sending responses etc. I am on virtual box (linux) machine, and using res always gives error (undefined methods etc.). Thanks in advance,
http.createServer(app).listen(port, [hostname], [backlog], [callback])
There are no parameters given to the callback function. This is why req and res are undefined.
So you may change your code to:
app.listen(port, function(){
console.log("Server running at: " + "http://localhost:" + port);
});
app.get('/', function(req,res) {
res.status(200).send('Hello World!')
})
So take a look at the documentation of app.listen() and app.get()

Node.js memory leak in streams

I detected a strange increase of the memory usage in an express.js application and after a lot of investigation I discovered that the problem was caused while writing to a file using writable streams.
To isolate the problem I created this simple app:
var express = require('express');
var http = require('http');
var path = require('path');
var fs = require('fs');
var app = express();
app.set('port', process.env.PORT || 3000);
var writable = fs.createWriteStream('/tmp/stream', {flags: 'a'});
var i = 1;
app.get('/', function (req, res) {
i = i + 1;
writable.write(i + '\n');
res.end();
});
app.get('/flush', function (req, res) {
writable.end();
res.end();
});
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
After launching several requests with a benchmark tool and analyzing the memory used with 'top', I realized that it grows and is never released.
The call to the flush route after finishing the requests doesn't free the memory either.
Is this a memory leak or I'm doing something wrong?
I've made the tests with node 0.8.6, 0.10.37 and 0.12.7 with the same results.

socket.io not working node.js

I am not able to run socket.io code in node.js, console.log() is also not displaying when running the code. Below is the code.
app.js
var express = require('express');
var http = require('http');
var app = express();
app.set('port', process.env.PORT || 3000);
app.post('/testStream',test.testStream);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
module.exports.appServer = server;
and I have created a test.js file where I am accessing this exported variable appServer.
var server = require('../app.js');
exports.testStream = function(req,res){
var io = require('socket.io').listen(server.appServer);
io.on('connection',function(socket){
console.log("in socket");
fs.readFile('E:/temp/testimg.png',function(err,buf){
socket.emit('image',{image: true,buffer: buf});
console.log("test image");
});
})
}
when the code runs it stucks and not showing the console.logs(). What I am doing wrong over here. Any help is very much appreciated.
I would suggest following the code structure as suggested in socket.io docs.
Also, you should not be calling io.listen or io.on('connection') inside your testStream express middleware. These are things you should only be doing once, and ideally they should happen during startup, inside app.js and not in reaction to a POST request. In fact, I'm not sure what the purpose of your testStream middleware is, its not even returning any response (eg res.end())
If you want to handle socket connections in a separate module you can, but instead of exporting your app's server the way you are, try passing the io instance as variable to your submodule. In short, try this:
app.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var test = require('./test')(io);
app.set('port', process.env.PORT || 3000);
server.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
test.js
module.exports = function(io) {
io.on('connection', function(socket) {
console.log("in socket");
fs.readFile('E:/temp/testimg.png', function(err, buf) {
socket.emit('image', {
image: true,
buffer: buf
});
console.log("test image");
});
});
};

Resources