I have started writing a node application and I want to store the request
and response
objects In a hashtable. For the hashtable I am using jshashtable
. When I store the request
and response
objects in the hashtable and fetch them later, I get a Object.keys called on non-object
error when trying to use response
, whether that be writeHead()
or simply just printing with console.log()
. However typeof
returns object
for response
, so it appears that response
is being manipulated when it's being stored in jshashtable
. On the jshashtable
website the author writes " 'Objects' here is used loosely to mean any JavaScript object or value. ", so It appears like I should be able to store any javascript object including the response
object.
jshashtable
can be installed with npm install jshashtable
.
Here is some code that replicates the issue.
var Hashtable = require('jshashtable');
var crypto = require('crypto');
var table = new Hashtable();
var http = require('http');
var fs = require("fs");
var home = fs.readFileSync('/some/random/html/home.html');
http.createServer(function(req, res) {
crypto.randomBytes(8, function(ex, buf) {
if (ex) throw ex;
var userID = buf.toString('hex');
var state = {
"req": req,
"res": res
}
table.put(userID, state);
var message = {
"httpCode": 200,
"humanCode": "OK",
"contentType": "text/html",
"data": home
};
dataOut(userID, message, function(err, rtrn) {
});
});
}).listen(80);
function dataOut(userID, message, callback) {
if(typeof callback === 'function') {
var state;
state = table.get(userID);
if(state === null) {
console.log("Can't get value");
callback("Can't get value from key.", null);
}
if(typeof state.res === 'object') {
console.log('This is an object');
}
//console.log(state.res);
state.res.writeHead(message.httpCode, message.humanCode, message.contentType);
state.res.write(message.data);
state.res.end();
}
}
So why can't I use request
and response
after storing them In jshashtable
?
The only error I encounter is on the state.res.writeHead...
on line 51. Commenting that out, works fine and I can use the response object. The error with res.writeHead
is how you pass arguments. It should be res.writeHead(status, {header_Name: header_value, another_header: another_value})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With