node.js - display error 404 - when required file fails -


new node.js not want use
frameworks design multi page web site.
idea grab url path name , add .js
extension , require it.

but happens when pathname not
correspond valid .js file required ?

node.js server crashes.

the question how display 'error 404' ?

var http = require('http'); var url = require('url');  var server=http.createserver(function(req,res){     res.writehead(200,{'content-type': 'text/html; charset=utf-8'});         var pathname=url.parse(req.url).pathname;     pathname = pathname.replace('-', '')     var page = require(pathname + '.js')     res.end(pathname + '.js included successfully')  }).listen(80); 

when run

domain.tld/22 

this script display

 " 22.js included " 

because have 22.js

but when try

 domain.tld/23 

the whole thing crashes. following error

module.js:339     throw err;     ^      error: cannot find module '/23.js'         @ function.module._resolvefilename (module.js:337:15)         @ function.module._load (module.js:287:25)         @ module.require (module.js:366:17)         @ require (module.js:385:17)         @ server.<anonymous> (/test.js:8:13)         @ emittwo (events.js:87:13)         @ server.emit (events.js:172:7)         @ httpparser.parseronincoming [as onincoming] (_http_server.js:528:12)         @ httpparser.parseronheaderscomplete (_http_common.js:88:23) 

put require in try ... catch block:

try {     require('nonexistent');     console.log('success'); } catch(e) {     console.log('failure',e); } 

however, think approach very, dangerous. @ least, should check presence of /s, .., etc. make sure modules intended allowed loaded can be.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -