http-proxy (reverse proxy) server hangs up in a random time - node.js

Problem: When I send a request after this log (memory), it shows "socket hang up (connResetException)" error. And the NodeJS server stops working.
[1:0x330e8a0] 22724 ms: Mark-sweep 16.4 (25.2) -> 10.6 (29.9) MB,
3.3 / 0.0 ms (+ 0.1 ms in 2 steps since start of marking, biggest step 0.1
ms, walltime since start of marking 7 ms) (average mu
= 0.999, current mu = 1.000) finalize incremental marking
via task GC in old space requested
Architecture: I use http-proxy as a reverse proxy. It enables the SSO(Single-Sign-On) and sends its traffics to the application.
Error Log in Proxy Server(Only happens in the production - more traffics)
/node_modules/http-proxy/lib/http-proxy/index.js:120
throw err;
^
Error: socket hang up
at connResetException (internal/errors.js:561:14)
at Socket.socketCloseListener (_http_client.js:380:25)
at Socket.emit (events.js:214:15)
at TCP.<anonymous> (net.js:658:12) {
code: 'ECONNRESET'
}
Since socket hangs up happens with MANY cases, I researched and experimented with various cases. And I'm thinking the memory leak issue from my node can be the issue.
node --trace_gc src/index.js commands print 2~3 allocation failures per request.
Weird logs
[1:0x449d780] 20364 ms: Scavenge 11.9 (13.2) -> 11.3 (13.2) MB, 3.2 / 0.0 ms \
(average mu = 0.961, current mu = 0.961) allocation failure
Source Code
var apiProxy = httpProxy.createProxyServer();
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())
app.use(passport.initialize({}));
app.use(passport.session({}));
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: true,}
));
app.get('/source*',
function(req, res, next) {
req.query.RelayState = req.url;
if(req.user) {
apiProxy.web(req, res, {target: xx});
Problem: [http-proxy expressjs] hangs up in a random time. It usually works for two days and the server goes 502 Error. I need to manually restart the container to restore it.
/node_modules/http-proxy/lib/http-proxy/index.js:120
throw err;
^
Error: socket hang up
at connResetException (internal/errors.js:561:14)
at Socket.socketCloseListener (_http_client.js:380:25)
at Socket.emit (events.js:214:15)
at TCP.<anonymous> (net.js:658:12) {
code: 'ECONNRESET'
}
Any idea is welcome... please help 🙏

Related

Unable to upload large files using nodejs/axios

I am writing a nodejs client that would upload files (files can be both binary or text files) from my local dev machine to my server which is written in Java, configuring which is not an option. I am using the following code to upload files, it works fine for files upto 2 gb, but beyond that it throws an error mentioned below. Now you may think that the server might not be allowing files more than 2 gb but I have successfully uploaded files upto 10 gb using Rest clients like Postman and Insomnia on the same instance.
const fs = require("fs");
const path = require("path");
const axios = require("axios");
const FormData = require("form-data");
function uploadAxios({ filePath }) {
let formData;
try {
formData = new FormData();
formData.append("filedata", fs.createReadStream(filePath));
} catch (e) {
console.error(e)
}
axios
.post(
`https://myinstance.com`,
formData,
{
headers: {
...formData.getHeaders(),
"Content-Type": "multipart/form-data",
Authorization:
"Basic xyz==",
},
maxContentLength: Infinity,
maxBodyLength: Infinity,
// maxContentLength: 21474836480,
// maxBodyLength: 21474836480, // I have tried setting these values with both numbers and the keyword Infinity but nothing works
}
)
.then(console.log)
.catch(console.error);
}
const filePath = "C:\\Users\\phantom007\\Documents\\BigFiles\\3gb.txt";
uploadAxios({ filePath });
Error I get:
#
# Fatal error in , line 0
# API fatal error handler returned after process out of memory
#
<--- Last few GCs --->
es[7844:0000023DC49CE190] 47061 ms: Mark-sweep 33.8 (41.8) -> 33.8 (41.8) MB, 417.2 / 0.1 ms (+ 947.1 ms in 34029 steps since start of marking, biggest step 431.0 ms, walltime since start of marking 15184 ms) finalize incremental marking via stack guard[7844:0000023D
C49CE190] 48358 ms: Mark-sweep 34.4 (41.8) -> 31.8 (40.5) MB, 1048.4 / 0.0 ms (+ 0.0 ms in 1 steps since start of marking, biggest step 0.0 ms, walltime since start of marking 1049 ms) finalize incremental marking via task GC in old spac
<--- JS stacktrace --->
==== JS stack trace =========================================
Security context: 000002E294C255E9 <JSObject>
0: builtin exit frame: new ArrayBuffer(aka ArrayBuffer)(this=0000022FFFF822D1 <undefined>,65536)
1: _read [fs.js:~2078] [pc=0000004AD942D301](this=0000039E67337641 <ReadStream map = 000002F26D804989>,n=65536)
2: read [_stream_readable.js:454] [bytecode=000002A16EB59689 offset=357](this=0000039E67337641 <ReadStream map = 000002F26D804989>,n=0)
3: push [_stream_readable.js:~201]...
FATAL ERROR: Committing semi space failed. Allocation failed - process out of memory
It looks like the error is because it has exceed the memory limit, i know by passing the flag --max-old-space-size i can overcome this, but i want this to be scalable and not hardcode an upper limit.
PS: My dev machine has 12 GB free memory
Edit: I added the error trace.
I'm using multer to define limit, see next code:
app.use(multer({
storage: storage,
dest: path.join(pathApp),
limits: {
fileSize: 5000000
},
fileFilter: function fileFilter(req, file, cb) {
var filetypes = /json/;
var mimetype = filetypes.test(file.mimetype);
var extname = filetypes.test(path.extname(file.originalname));
if (mimetype && extname) {
console.log("Port ".concat(app.get('port')) + " - Uploading file " + file.originalname);
return cb(null, true, req);
}
cb(JSON.stringify({
"success": false,
"payload": {
"app": "upload",
"function": "upload"
},
"error": {
"code": 415,
"message": 'File type not valid'
}
}));
}
}).single('file1'));

How to load very large csv files in nodejs?

I'm trying to load 2 big csv into nodejs, first one has a size of 257 597 ko and second one 104 330 ko. I'm using the filesystem (fs) and csv modules, here's my code :
fs.readFile('path/to/my/file.csv', (err, data) => {
if (err) console.err(err)
else {
csv.parse(data, (err, dataParsed) => {
if (err) console.err(err)
else {
myData = dataParsed
console.log('csv loaded')
}
})
}
})
And after ages (1-2 hours) it just crashes with this error message :
<--- Last few GCs --->
[1472:0000000000466170] 4366473 ms: Mark-sweep 3935.2 (4007.3) -> 3935.2 (4007.
3) MB, 5584.4 / 0.0 ms last resort GC in old space requested
[1472:0000000000466170] 4371668 ms: Mark-sweep 3935.2 (4007.3) -> 3935.2 (4007.
3) MB, 5194.3 / 0.0 ms last resort GC in old space requested
<--- JS stacktrace --->
==== JS stack trace =========================================
Security context: 000002BDF12254D9 <JSObject>
1: stringSlice(aka stringSlice) [buffer.js:590] [bytecode=000000810336DC91 o
ffset=94](this=000003512FC822D1 <undefined>,buf=0000007C81D768B9 <Uint8Array map
= 00000352A16C4D01>,encoding=000002BDF1235F21 <String[4]: utf8>,start=0,end=263
778854)
2: toString [buffer.js:664] [bytecode=000000810336D8D9 offset=148](this=0000
007C81D768B9 <Uint8Array map = 00000352A16C4D01>,encoding=000002BDF1...
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memo
ry
1: node::DecodeWrite
2: node_module_register
3: v8::internal::FatalProcessOutOfMemory
4: v8::internal::FatalProcessOutOfMemory
5: v8::internal::Factory::NewRawTwoByteString
6: v8::internal::Factory::NewStringFromUtf8
7: v8::String::NewFromUtf8
8: std::vector<v8::CpuProfileDeoptFrame,std::allocator<v8::CpuProfileDeoptFrame
> >::vector<v8::CpuProfileDeoptFrame,std::allocator<v8::CpuProfileDeoptFrame> >
9: v8::internal::wasm::SignatureMap::Find
10: v8::internal::Builtins::CallableFor
11: v8::internal::Builtins::CallableFor
12: v8::internal::Builtins::CallableFor
13: 00000081634043C1
The biggest file is loaded but node runs out of memory for the other. It's probably easy to allocate more memory, but the main issue here is the loading time, it seems very long despite the size of files. So what is the correct way to do it? Python loads these csv really fast with pandas btw (3-5 seconds).
Stream works perfectly, it took only 3-5 seconds :
var csv = require('csv-parser')
var data = []
fs.createReadStream('path/to/my/data.csv')
.pipe(csv())
.on('data', function (row) {
data.push(row)
})
.on('end', function () {
console.log('Data loaded')
})
fs.readFile will load the entire file into memory, but fs.createReadStream will read the file in chunks of the size you specify.
This will prevent it from running out of memory
You may want to stream the CSV, instead of reading it all at once:
csv-parse has streaming support: http://csv.adaltas.com/parse/
or, you may want to take a look at csv-stream: https://www.npmjs.com/package/csv-stream

Node-Postgres: program does not work after 30 seconds while using Express, no problems without Express

I am using node-postgres to connect to a Postgres database from NodeJS; it gives a strange error Cannot read property 'rows' of undefined after running the program for 30 seconds (after the first request to the server). The error vanishes if I don't use Express.
I have stripped down the code to reproduce the error:
1 var conn_string = "pg://postgres#localhost:5432/foobardb";
2 var express = require("express");
3 var pg = require("pg");
4 var router_home = express.Router();
5 var app = express();
6
7 pg.connect(conn_string, function(err, client, done){
8 router_home.get("/", function(req, res, next){
9 client.query("select * from visit", function(err, result){
10 done();
11 res.end(JSON.stringify(result.rows[0]));
12 });
13 });
14 });
15 app.use("/", router_home);
16 app.listen(8080);
Running curl -X GET http://localhost:8080/ on this code sample works perfectly fine the first few times, and then fails after 30 seconds (after running it the first time) and gives the error below:
TypeError: Cannot read property 'rows' of undefined
at null.callback (/Users/yc/nodeProjects/pgExpress.js:11:33)
at Query.handleError (/Users/yc/nodeProjects/node_modules/pg/lib/query.js:106:17)
at null.<anonymous> (/Users/yc/nodeProjects/node_modules/pg/lib/client.js:171:26)
at emitOne (events.js:90:13)
at emit (events.js:182:7)
at Socket.<anonymous> (/Users/yc/nodeProjects/node_modules/pg/lib/connection.js:59:10)
at emitOne (events.js:90:13)
at Socket.emit (events.js:182:7)
at Socket.writeAfterFIN [as write] (net.js:281:8)
at Connection.query (/Users/yc/nodeProjects/node_modules/pg/lib/connection.js:189:15)
If I rewrite the same program without using Express, it works just fine, indefinitely.
1 var conString = "pg://postgres#localhost:5432/foobardb";
2
3 var http = require('http');
4 var pg = require('pg');
5
6 var server = http.createServer(function(req, res) {
7 pg.connect(conString, function(err, client, done) {
8
9 client.query("select * from visit", function(err, result) {
10 done();
11 res.end(JSON.stringify(result.rows[0]));
12 });
13 });
14 });
15 server.listen(3001);
Except the use of Express, the code is identical. I am really confused. My guess is it might have to do with caching, although why it disappears when I don't use Express is beyond me. A fix, or how to work around this (while still using Express) would be most appreciated!
It is not about express, it is about your broken logic for the database connection.
In your initial code you first connect to the database, then you set the HTTP listener, then you make the query, then release the connection. On the second call already you will be leaking your connection. The logic of what you are doing is completely broken.
You are supposed to do it like this: set up the HTTP listener, and once you get the request, connect to the database, make query, release the connection.
And if you want a simpler approach where you don't need to care about the connection, check out pg-promise ;)

OpenShift MongoError: auth fails how to resolve?

EDIT ; attaching my app.js , I am using
git add app.js
git commit -m "updated app.js"
git push
command to push code from local machine, and my app.js code is as follows :
/*
*RESTfull server
*/
//defining express middleware
var express=require('express');
//require mongoose, this middleware helps in modeling data for mongodb
var mongoose=require('mongoose');
//require passport, this middleware helps in authentiation
var passport=require('passport');
//require passport, this middleware parsing body
var bodyParser = require('body-parser');
var flash = require('connect-flash');
//define port on which node app is gonna run
//var port = process.env.PORT || 8000;
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080 ;
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1' ;
var app=express();
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
======================================================================
app.listen(server_port,server_ip_address);
console.log('The magic happens on port ' + 'http://'+server_ip_address+':'+server_port);
EDIT :
I commented all mongodb connection code, now my app.js has simple expressjs code, still I can see the same output from the command "rhc tail -a app", Iam not sure why nodejs catridge is trying to connect to mongodb, eventhough there is no code in app.js, is it possible that the log has been generated previously and the same log is being shown ? can I clear log file and test it once? can somebody please help me.
I deployed my nodejs(expressjs) app to the openshift server. I am hitting a mongoError "MongoError: auth fails", I am providing credentials to mongodb server.
Initially when node child process starts it is trying to connect to the
"mongodb://admin:XXXXXX#ip:port" but it should connect to "mongodb://admin:XXXXXX#ip:port/admin" as credentials reside in admin.system.users collection.
I am using mongoose to connect to mongoDB so I changed my mongoose connect to
mongoose.connect(mongodb://admin:XXXXXX#ip:port/admin); But I still see child process is trying to connect to this url "mongodb://admin:XXXXXX#ip:port", but later point of time it connects to the correct collection, and I can see the console ouput of the following code.
mongoose.connection.once('connected', function() {
console.log("Connected to database G")
});
I tested few routes, they are working fine. I want to understand why is it behaving so and can I ignore this error or how can I resolve this issue??
Thanks in advance.
You should be using process.env.OPENSHIFT_MONGODB_DB_URL instead of forming your own url. This environment variable has the following format:
mongodb://admin:LX3eZCP6yxxx#123e4b9a5973ca07ca00002f-appname.rhcloud.com:12345/
Attaching my "rhc tail -a app" commad,
==> app-root/logs/nodejs.log-20150328020443 <==
DEBUG: Starting child process with 'node app.js'
mongodb://admin:pass#550f3e705973cab149000009-app.rhcloud.com:59281/
mongodb://admin:pass#550f3e705973cab149000009-app.rhcloud.com:59281/
The magic happens on port http://127.9.17.129:8080
/var/lib/openshift/550f3c0ffcf933066f0001b8/app-root/runtime/repo/node_modules/m
ongoose/node_modules/mongodb/lib/mongodb/connection/base.js:246
throw message;
^
MongoError: auth fails
at Object.toError (/var/lib/openshift/550f3c0ffcf933066f0001b8/app-root/runt
ime/repo/node_modules/mongoose/node_modules/mongodb/lib/mongodb/utils.js:114:11)
at /var/lib/openshift/550f3c0ffcf933066f0001b8/app-root/runtime/repo/node_mo
dules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1194:31
==> app-root/logs/nodejs.log-20150327071155 <==
at EventEmitter.emit (events.js:98:17)
DEBUG: Program node app.js exited with code 8
DEBUG: Starting child process with 'node app.js'
mongodb://admin:pass#550f3e705973cab149000009-app.rhcloud.com:59281/
mongodb://admin:pass#550f3e705973cab149000009-app.rhcloud.com:59281/
The magic happens on port http://127.9.17.129:8080
/var/lib/openshift/550f3c0ffcf933066f0001b8/app-root/runtime/repo/node_modules/m
ongoose/node_modules/mongodb/lib/mongodb/connection/base.js:246
throw message;
^
MongoError: auth fails
==> app-root/logs/nodejs.log <==
DEBUG: program 'app.js'
DEBUG: --watch '/var/lib/openshift/550f3c0ffcf933066f0001b8/app-root/data/.nod
ewatch'
DEBUG: --ignore 'undefined'
DEBUG: --extensions 'node|js|coffee'
DEBUG: --exec 'node'
DEBUG: Starting child process with 'node app.js'
DEBUG: Watching directory '/var/lib/openshift/550f3c0ffcf933066f0001b8/app-root/
data/.nodewatch' for changes.
admin:pass#550f3e705973cab149000009-app.rhcloud.com:59281
The magic happens on port http://127.9.17.129:8080
Connected to database G
==> app-root/logs/haproxy.log <==
[WARNING] 087/140540 (417258) : Server express/local-gear is UP, reason: Layer7
check passed, code: 200, info: "HTTP status check returned code <3C>200<3E>", ch
eck duration: 1ms. 1 active and 0 backup servers online. 0 sessions requeued, 0
total in queue.
[WARNING] 088/001408 (417258) : Server express/local-gear is DOWN, reason: Layer
4 connection problem, info: "Connection refused", check duration: 0ms. 0 active
and 0 backup servers left. 0 sessions active, 0 requeued, 0 remaining in queue.
[ALERT] 088/001408 (417258) : proxy 'express' has no server available!
[WARNING] 088/002019 (417258) : Server express/local-gear is UP, reason: Layer7
check passed, code: 200, info: "HTTP status check returned code <3C>200<3E>", ch
eck duration: 29ms. 1 active and 0 backup servers online. 0 sessions requeued, 0
total in queue.
[WARNING] 088/110018 (417258) : Server express/local-gear is DOWN, reason: Layer
4 connection problem, info: "Connection refused", check duration: 0ms. 0 active
and 0 backup servers left. 0 sessions active, 0 requeued, 0 remaining in queue.
[ALERT] 088/110018 (417258) : proxy 'express' has no server available!
[WARNING] 088/110112 (417258) : Server express/local-gear is UP, reason: Layer7
check passed, code: 200, info: "HTTP status check returned code <3C>200<3E>", ch
eck duration: 1ms. 1 active and 0 backup servers online. 0 sessions requeued, 0
total in queue.
[WARNING] 088/110502 (417258) : Server express/local-gear is DOWN, reason: Layer
4 connection problem, info: "Connection refused", check duration: 0ms. 0 active
and 0 backup servers left. 0 sessions active, 0 requeued, 0 remaining in queue.
[ALERT] 088/110502 (417258) : proxy 'express' has no server available!
[WARNING] 088/110556 (417258) : Server express/local-gear is UP, reason: Layer7
check passed, code: 200, info: "HTTP status check returned code <3C>200<3E>", ch
eck duration: 1ms. 1 active and 0 backup servers online. 0 sessions requeued, 0
total in queue.
==> app-root/logs/nodejs.log-20150328074316 <==
The magic happens on port http://127.9.17.129:8080
/var/lib/openshift/550f3c0ffcf933066f0001b8/app-root/runtime/repo/node_modules/m
ongoose/node_modules/mongodb/lib/mongodb/connection/base.js:246
throw message;
^
MongoError: auth fails
at Object.toError (/var/lib/openshift/550f3c0ffcf933066f0001b8/app-root/runt
ime/repo/node_modules/mongoose/node_modules/mongodb/lib/mongodb/utils.js:114:11)
at /var/lib/openshift/550f3c0ffcf933066f0001b8/app-root/runtime/repo/node_mo
dules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1194:31
at /var/lib/openshift/550f3c0ffcf933066f0001b8/app-root/runtime/repo/node_mo
dules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1903:9
at Server.Base._callHandler (/var/lib/openshift/550f3c0ffcf933066f0001b8/app
-root/runtime/repo/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connec
tion/base.js:453:41)
at /var/lib/openshift/550f3c0ffcf933066f0001b8/app-root/runtime/repo/node_mo
dules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:487:18
==> app-root/logs/haproxy_ctld.log <==
I, [2015-03-22T18:06:38.808186 #415579] INFO -- : Starting haproxy_ctld
I, [2015-03-27T14:20:21.556898 #15736] INFO -- : Starting haproxy_ctld
I, [2015-03-29T12:18:29.365873 #417278] INFO -- : Starting haproxy_ctld
I, [2015-03-29T12:18:37.485326 #417532] INFO -- : Starting haproxy_ctld
==> app-root/logs/nodejs.log-20150323084556 <==
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/var/lib/openshift/550f3c0ffcf933066f0001b8/app-root/
runtime/repo/app.js:43:16)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
DEBUG: Program node app.js exited with code 8
==> app-root/logs/nodejs.log-20150328012640 <==
at /var/lib/openshift/550f3c0ffcf933066f0001b8/app-root/runtime/repo/node_mo
dules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1194:31
at /var/lib/openshift/550f3c0ffcf933066f0001b8/app-root/runtime/repo/node_mo
dules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1903:9
at Server.Base._callHandler (/var/lib/openshift/550f3c0ffcf933066f0001b8/app
-root/runtime/repo/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connec
tion/base.js:453:41)
at /var/lib/openshift/550f3c0ffcf933066f0001b8/app-root/runtime/repo/node_mo
dules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:487:18
at MongoReply.parseBody (/var/lib/openshift/550f3c0ffcf933066f0001b8/app-roo
t/runtime/repo/node_modules/mongoose/node_modules/mongodb/lib/mongodb/responses/
mongo_reply.js:68:5)
at null.<anonymous> (/var/lib/openshift/550f3c0ffcf933066f0001b8/app-root/ru
ntime/repo/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/ser
ver.js:445:20)
at EventEmitter.emit (events.js:95:17)
at null.<anonymous> (/var/lib/openshift/550f3c0ffcf933066f0001b8/app-root/ru
ntime/repo/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/con
nection_pool.js:207:13)
at EventEmitter.emit (events.js:98:17)
DEBUG: Program node app.js exited with code 8

Apachebench request count and Node.js script counter don't match

No doubt I'm doing something stupid, but I've been having problems running a simple node.js app using the Nerve micro-framework. Testing with apachebench, it seems that the code within my single controller is being invoked more frequently than the app itself is being called.
I've created a test script like so:
'use strict';
(function () {
var path = require('path');
var sys = require('sys');
var nerve = require('/var/www/libraries/nerve/nerve');
var nerveCounter = 0;
r_server.on("error", function (err) {
console.log("Error " + err);
});
var app = [
["/", function(req, res) {
console.log("nc = " + ++nerveCounter);
}]
];
nerve.create(app).listen(80);
}());
Start the server. From another box, run a load test:
/usr/sbin/ab -n 5000 -c 50 http://<snip>.com/
...
Complete requests: 5000
...
Percentage of the requests served within a certain time (ms)
...
100% 268 (longest request)
But the node script itself is printing all the way up to:
nc = 5003
rc = 5003
In other words, the server is being called 5000 times but the controller code is being called 5003 times.
Any ideas what I'm doing wrong?
Updated
I changed the tone and content of this question significantly to reflect the help Colum, Alfred and GregInYEG gave me in realising that the problem did not lie with Redis or Nerve and probably lie with apachebench.
Program:
const PORT = 3000;
const HOST = 'localhost';
const express = require('express');
const app = module.exports = express.createServer();
const redis = require('redis');
const client = redis.createClient();
app.get('/incr', function(req, res) {
client.incr('counter', function(err, reply) {
res.send('incremented counter to:' + reply.toString() + '\n');
});
});
app.get('/reset', function(req, res) {
client.del('counter', function(err, reply) {
res.send('resetted counter\n');
});
});
app.get('/count', function(req, res) {
client.get('counter', function(err, reply) {
res.send('counter: ' + reply.toString() + '\n');
});
});
if (!module.parent) {
app.listen(PORT, HOST);
console.log("Express server listening on port %d", app.address().port);
}
Conclusion
It works without any flaws on my computer:
$ cat /etc/issue
Ubuntu 10.10 \n \l
$ uname -a
Linux alfred-laptop 2.6.35-24-generic #42-Ubuntu SMP Thu Dec 2 01:41:57 UTC 2010 i686 GNU/Linux
$ node -v
v0.2.6
$ npm install express hiredis redis
npm info build Success: redis#0.5.2
npm info build Success: express#1.0.3
npm info build Success: hiredis#0.1.6
$ ./redis-server --version
Redis server version 2.1.11 (00000000:0)
$ git clone -q git#gist.github.com:02a3f7e79220ea69c9e1.git gist-02a3f7e7; cd gist-02a3f7e7; node index.js
$ #from another tab
$ clear; curl http://localhost:3000/reset; ab -n 5000 -c 50 -q http://127.0.0.1:3000/incr > /dev/null; curl http://localhost:3000/count;
resetted counter
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking 127.0.0.1 (be patient)
Completed 500 requests
Completed 1000 requests
Completed 1500 requests
Completed 2000 requests
Completed 2500 requests
Completed 3000 requests
Completed 3500 requests
Completed 4000 requests
Completed 4500 requests
Completed 5000 requests
Finished 5000 requests
Server Software:
Server Hostname: 127.0.0.1
Server Port: 3000
Document Path: /incr
Document Length: 25 bytes
Concurrency Level: 50
Time taken for tests: 1.172 seconds
Complete requests: 5000
Failed requests: 4991
(Connect: 0, Receive: 0, Length: 4991, Exceptions: 0)
Write errors: 0
Total transferred: 743893 bytes
HTML transferred: 138893 bytes
Requests per second: 4264.61 [#/sec] (mean)
Time per request: 11.724 [ms] (mean)
Time per request: 0.234 [ms] (mean, across all concurrent requests)
Transfer rate: 619.61 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.5 0 7
Processing: 4 11 3.3 11 30
Waiting: 4 11 3.3 11 30
Total: 5 12 3.2 11 30
Percentage of the requests served within a certain time (ms)
50% 11
66% 13
75% 14
80% 14
90% 15
95% 17
98% 19
99% 24
100% 30 (longest request)
counter: 5000

Resources