简体   繁体   English

如何在不使用npm包的情况下编写vanilla nodejs路由器

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

For example I have a server.js 例如,我有一个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? 我有三个控制器Blog,Todo和Auth在restify,express或hapi中执行此操作很简单但是如何在不使用任何npm包的情况下编写路由文件?

Do I need to write require(./routes)(server) ? 我是否需要编写require(./routes)(server) and then function routes(server) {} module.exports = routes ? 然后是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. 您还需要导入url来解析url,然后检查路径。 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! 请注意,这基本上是adeneo在上面的评论中所说的!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM