angry kiwi
angry kiwi

Reputation: 11445

node.Js - how run different pages?

so when enter the url: http://mysite.com/ there will be loading the server.js file (the index file). I want load the account.js when I enter url http://mysite.com/account.

How to do that?

Upvotes: 0

Views: 2760

Answers (3)

nponeccop
nponeccop

Reputation: 13677

It is better to use request routers - see connect and express NPM modules. Manual path comparison does not scale - it will turn your code into nightmare as you add more and more URLs.

For a standalone router, see clutch NPM module, but router inside connect is more mature and can be used in a standalone way. express is an extension of connect, so it uses the router from connect.

Upvotes: 0

Emmerman
Emmerman

Reputation: 2343

Nodejs is a daemon. It doesn't load scripts every time you making request. You can use something like that:

var severs = require('server.js'),
    accounts = require('accounts.js');

require('http').createServer(function (req, res) {
    var path = require('url').parse(req.url).pathname;
    res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});

    if (path == '/account') {
        res.end(accounts.run());
    } else {
        res.end(severs.run());
    }
}).listen(80);

Upvotes: 0

neeebzz
neeebzz

Reputation: 11538

In server.js , on top include account.js >

var account = require("./account");

In your createServer function in nodejs, you check if the URI is /account >

//Create Server
http.createServer(function (request, response) {
    // Parse the entire URI to get just the pathname
    var uri = url.parse(request.url).pathname, query;
        if (uri == "/account") //If it's mysite.com/account
        {
            request.setEncoding("utf8");
            request.content = '';
                        //call account.whatever() to route to your account     functionality 
                        //send the response from it

        }
            else if (uri == "/") //It's mysite.com
            {   
                      //call whatever you have in the current server.js
            }
}).listen(8080);

Upvotes: 1

Related Questions