Kenichi Shibata Kenichi Shibata - 10 months ago 27
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) {
{'Content-Type' : 'text/plain'});

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

server.listen(environment.port);;'Server running at'+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
? and then
function routes(server) {} module.exports = routes

Is there a more readable way?


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') {
      fs.readFile(__dirname + '/assets/hifive.jpg', function(err, data) {
        if (err) console.log(err);
        response.end(data, 'utf-8');
    else {