Kenichi Shibata Kenichi Shibata - 7 months ago 10
Javascript Question

How do you write a vanilla nodejs router without using npm package

For example I have a server.js

'use strict';
var http, bunyan, config;

config = require('config');
http = require('http');
bunyan = require('bunyan');

//require('./routes/'); ?

process.env.TZ = 'UTC';
process.env.NODE_ENV = process.env.NODE_ENV || 'staging';
var environment = config.get('environment');

var log = bunyan.createLogger({
name : 'index',
level : 'debug',
stream : process.stdout,
});

var server = http.createServer(function (request, response) {
response.writeHead(200,
{'Content-Type' : 'text/plain'});
});

server.on('error', function(error){
log.error('Errored with the message: ',error);
process.exit(1);
});

server.listen(environment.port);
log.info(process.env.NODE_ENV);
log.info('Server running at http://0.0.0.0:'+environment.port+'/');


I have three controllers Blog, Todo and Auth It is trivial to do this in restify, express or hapi but how do I write routing file without using any npm packages?

Do I need to write
require(./routes)(server)
? and then
function routes(server) {} module.exports = routes
?

Is there a more readable way?

Answer

You need to also import url to parse the url, then check the path. From there you can send back what you want, in the code below it is an image from a file:

Note this is basically what adeneo has stated in the comment above!

http.createServer(function (request, response) {
  var path = url.parse(request.url, true).pathname;

  if (request.method === 'POST') {
    if (path === '/hifive') {
      response.writeHead(200,{'Content-Type':'image/jpg'});
      fs.readFile(__dirname + '/assets/hifive.jpg', function(err, data) {
        if (err) console.log(err);
        response.end(data, 'utf-8');
      })
    }
    else {
     response.end(404);
   }
 }
Comments