Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I store a response object In a hashtable?

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?

like image 300
2trill2spill Avatar asked May 26 '15 21:05

2trill2spill


1 Answers

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})

like image 93
Bwaxxlo Avatar answered Nov 13 '22 22:11

Bwaxxlo