The correct answer: I just add a working example without express.js, but a route dispatcher .
var http = require('http');
var Router = require('routes');
var router = Router();
var fs = require('fs')
router.addRoute("GET /test", (req, res, params) => {
let file = __dirname + '/views/test.html'
res.writeHead(200, {"Content-Type": "text/html"});
fs.createReadStream(file).pipe(res);
});
var server = http.createServer((req, res) => {
var match = router.match(req.method + ' ' + req.url);
if (match) match.fn(req, res, match.params);
else {
res.statusCode = 404;
res.end('not found\n');
}
}).listen(process.env.PORT || 3000);
the calling endpoint /testwill return views/test.html.
package.json is,
{
"name": "node-app",
"version": "1.0.0",
"description": "node api",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "prayagupd",
"license": "ISC",
"dependencies": {
"request": "^2.75.0",
"request-promise": "^4.1.1",
"routes": "^2.1.0"
}
}
source
share