0

I have a simple node.js server/client program, I wanted to change my existing code so that I could use object literals instead of switch statements, this is the code with switch/case which works fine:

const readline = require('readline'); 
const net = require('net'); 
const fs = require('fs'); 
var jsonName = "bands.json";
var r1 = readline.createInterface({
  input : process.stdin,
  output : process.stdout
});

r1.question('Test',function(answer){
  var server = net.createServer({allowHalfOpen:true},function(connection){
    connection.allowHalfOpen = true;
      data = data.toString().trim();
      switch(data)
      {
        case '/bands':
        {
          fs.readFile(jsonName,function(err,jsonContent){
            if(err)
              throw err;
              connection.write(jsonContent);
          });
          break;
        }
        //and other cases...
      }
    });
  });

I defined a function outside of the r1.question body as :

function handleRequest(data){
      var response = {
        '/bands': function(){
          fs.readFile(jsonName,function(err,jsonContent){
            if(err)
              throw err;
            return jsonContent;
          });
        },
        '/notFound':function(){
          return "Unknown Command, Try again...";
        }
      };
      return (response[data] || response['/notFound'])();
    }

and called this function as :

  var response = handleRequest(data);
  connection.write(response);

However my response variable is undefined and it appears to be because my program doesnt wait for the handleRequest function to return the data read from the file and throws me this error:

net.js:641
    throw new TypeError('invalid data');
    ^

TypeError: invalid data
    at Socket.write (net.js:641:11)
    at Socket.<anonymous> (Path to my folder\server.js:37:22)
    at emitOne (events.js:77:13)
    at Socket.emit (events.js:169:7)
    at readableAddChunk (_stream_readable.js:153:18)
    at Socket.Readable.push (_stream_readable.js:111:10)
    at TCP.onread (net.js:536:20) 

Is there a way to use object literals asynchronously or should I stick with my switch/case scenario as it was?

  • It's nothing to do with the object literal per se. It's just that in addition to changing over to using an object to dispatch to the right function (which is fine), you're *also* trying to use the data before it arrives. You'd have the same problem if you tried to use the data immediately after the `switch`. – T.J. Crowder Dec 09 '16 at 16:58
  • (Side note: `case` doesn't require a block.) – T.J. Crowder Dec 09 '16 at 16:58

0 Answers0