Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8216975
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T12:19:11+00:00 2026-06-07T12:19:11+00:00

Homework done: The Node Beginner Book How do I get started with Node.js [closed]

  • 0

Homework done:

The Node Beginner Book

How do I get started with Node.js [closed]

Structuring handlers in Node

Backstory: I wanted to try and write my own framework but I’m running into some troubles, most likely due to not understanding it fully.

What I want to achieve is a syntax that looks like this:

var app = require('./app'); //this part is understood and it works in my current code.
app.get('/someUrl', function(){ //do stuff here });
app.post('/someOtherUrl', function(){ //do stuff here });

I know of the Express-framework that has this same syntax but reading their source code still eludes me.

This might be a trivial task to achieve but I simply can’t produce it, yet.

Trying to require('./app'); in a file deeper in the application produces a undefined object, so I’m guessing that a server is a singleton object.

So what have I tried?

My current code looks like this, and somehow I feel like this is the way to go, but I can’t apparently do it like this.

I’m omitting all the require(); statements to keep it more readable.

server.js:

var app = module.exports = {
    preProcess: function onRequest(request, response){
        processor.preRequest(request); //this object adds methods on the request object
        var path = urllib.parse(request.url).pathname;
        router.route(urls, path, request, response);
    },
    createServer: function() {
        console.log("Server start up done.");
        return this.server = http.createServer(this.preProcess);
    }
};

exports.app = app;

At the time of writing I’m experimenting with extending this object with a get() method.

index.js:

var app = require('./server');
app.createServer().listen('1337');

the router.route() bit basically sends the request onward into the application and inside the router.js-file I do some magic and route the request onward to a function that maps (so far) to the /urlThatWasRequested

This is the behavior I’d like to leave behind.
I know this might be a pretty tall order but all my code is easily discardable and I’m not afraid of rewriting the entire codebase as this is my own project.

I hope this is sufficient in explaining my question otherwise, please say what I should add to make this a bit more clear.

Thanks in advance!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T12:19:12+00:00Added an answer on June 7, 2026 at 12:19 pm

    I’m not exactly sure what your question is, but here’s some thoughts:

    1) You are creating a circular reference here:

    var app = module.exports = {
        // some other code
    }
    exports.app = app;
    

    You add app as a property of app. There’s no need for the last line.

    2) You need to hold handlers in app. You can try something like this:

    var app = module.exports = {
        handlers : [],
        route : function(url, fn) {
            this.handlers.push({ url: url, fn: fn });
        },
        preProcess: function onRequest(request, response){
            processor.preRequest(request);
            var path = urllib.parse(request.url).pathname;
            var l = this.handlers.length, handler;
            for (var i = 0; i < l; i++) {
                handler = this.handlers[i];
                if (handler.url == path)
                    return handler.fn(request, response);
            }
            throw new Error('404 - route does not exist!');
        },
        // some other code
    }
    

    Note that you may alter this line: if (handler.url == path) in such a way that handler.url is a regular expression and you test path against it. Of course you may implement .get and .post variants, but from my experience it is easier to check whether a request is GET or POST inside the handler. Now you can use the code above like this:

    app.route('/someUrl', function(req, res){ //do stuff here });
    

    The other thing is that the code I’ve shown you only fires the first handler for a given URL it matches. You would probably want to make more complex routes involving many handlers (i.e. middlewares). The architecture would be a bit different in that case, for example:

    preProcess: function onRequest(request, response){
        var self = this;
        processor.preRequest(request);
        var path = urllib.parse(request.url).pathname;
        var l = self.handlers.length,
            index = 0,
            handler;
        var call_handler = function() {
            var matched_handler;
            while (index < l) {
                handler = self.handlers[index];
                if (handler.url == path) {
                    matched_handler = handler;
                    break;
                }
                index++;
            }
            if (matched_handler)
                 matched_handler.fn(request, response, function() {
                     // Use process.nextTick to make it a bit more scalable.
                     process.nextTick(call_handler);
                 });
            else
                 throw new Error('404: no route matching URL!');
         };
         call_handler();
    },
    

    Now inside your route you can use

    app.route('/someUrl', function(req, res, next){ 
        //do stuff here
        next(); // <--- this will take you to the next handler
    });
    

    which will take you to another handler (or throw exception if there are no more handlers).

    3) About these words:

    Trying to require(‘./app’); in a file deeper in the application produces a undefined
    object, so I’m guessing that a server is a singleton object.

    It isn’t true. require always returns the reference to the module object. If you see undefined, then you’ve messed up something else (altered the module itself?).

    Final note: I hope it helps a bit. Writing your own framework can be a difficult job, especially since there already are excelent frameworks like Express. Good luck though!

    EDIT

    Implementing .get and .set methods is actually not difficult. You just need to alter route function like this:

    route : function(url, fn, type) {
        this.handlers.push({ url: url, fn: fn, type: type });
    },
    get : function(url, fn) {
        this.route(url, fn, 'GET');
    },
    post : function(url, fn) {
        this.route(url, fn, 'POST');
    },
    

    and then in routing algorithm you check whether type property is defined. If it is not then use that route (undefined type means: always route). Otherwise additionally check if a request’s method matches type. And you’re done!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am a quite new to node js and have done some homework in
I've done my homework - I swear, I've been researching this for a bit.
If I have done my homework correctly, I have come to learn that Backbone
Alright, i had this homework recently (don't worry, i've already done it, but in
I'm stuck with this Java homework question: Write a new method, Refund, that simulates
I've done some homework on this and understand the basic rules of Version Control.
I have done a homework assignment, here is the problem statement: Your program should
I've done my homework and scoured SO to no avail. I've even gone from
I am new to linq and linq2SQL. I have done my homework, i.e. found
I've done some homework on this issue and I am pretty sure it will

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.