Chapter 2: Running Autoloader and Autoload Context - AlexanderSychev/node-autoload GitHub Wiki

Out first application with Autoloader

When you define you autoloadable modules you just need to call "run" function with array of directories paths which contains modules to automatic load. Paths must be absolute, not relative (use Node.JS module "path" to calc them)!

Let's create very simple site application with several pages. We will be use "node-autoload" and "express" as dependencies.

At the first of all, create project directory, switch to it and make empty "package.json" file:

mkdir node-autoload-example
cd ./node-autoload-example
touch ./package.json

In package.json we define two dependencies ("node-autoload" and "express"):

{
  "name": "node-autoload-example",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "4.15.2",
    "node-autoload": "0.0.2"
  }
}

Then install dependencies:

npm i

The next step is create project structure:

mkdir -p ./modules/page
mkdir -p ./modules/server

Now we are ready to develop.

At the first, we create module with Express Application instance - file "./modules/server/index.auto.js" with this code:

// We will use "Module" class to define module but it is not necessary
const Module = require('node-autoload').Module;
const express = require('express');

module.exports = new Module(
    'Server', // Module identifier
    function(context) { // Bootstrap function
        let app = express();
        return app; // Export instance
    },
    true // Module with "lazy" load - bootstraps on first "context.getModule" call
);

Then we create to pages: "Main" and "About" and attach them to application.

Create "./modules/pages/main.auto.js":

'use strict';

// Page content
const MAIN_HTML =
`<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Main</title>
    </head>
    <body>
        <h1>Node Autoloader Site</h1>
        <a href="/about">About</a>
        <a href="/feedback">Feedback</a>
    </body>
</html>
`;

// Here we use module implementation withoud "Module" class

exports.id = 'Page::Main'; // Identifier

exports.lazy = false; // Page modules must be executed immediately

exports.bootstrap = function(context) {
    // Require Express Application instance (module "Server")
    const Server = context.getModule('Server');

    // Attach route and handler to Express Application instance
    Server.get('/', function(req, res) {
        res.status(200);
        res.send(MAIN_HTML);
    });
};

Create "./modules/pages/about.auto.js", with same code:

'use strict';

const ABOUT_HTML =
`<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>About</title>
    </head>
    <body>
        <h1>About this site use Node Autoloader</h1>
    </body>
</html>
`;

exports.id = 'Page::About';

exports.lazy = false;

exports.bootstrap = function(context) {
    const Server = context.getModule('Server');
    Server.get('/about', function(req, res) {
        res.status(200);
        res.send(ABOUT_HTML);
    });
};

Last module to autoload - common site module which exports function "app" with one argument - TCP port to listen.

'use strict';

exports.id = 'App';

exports.bootstrap = function(context) {
    const Server = context.getModule('Server');

    const run = function(port) {
        Server.listen(port);
    };

    return {run: run};
};

Main executable file of site must run Autoload and return Autoload Context. In project root directory create file "index.js" with code:

'use strict';
// This is main function of Autoloader - it search modules by pattern, require them,
// executes all not lazy modules and returns context.
const run = require('node-autoload').run;

// To calc absolute path we use "join" function
const join = require('path').join;

// Run Autoloader and return context
const context = run([
    join(__dirname, 'modules')
]);

// Require main site module and start it
context.getModule('App').run(3000);

You can see your site at "http://localhost:3000" - all pages automaticaly loaded and mounted to application.

We may add other pages and don't think about paths or forgot to call them - they will be called and mounted automaticaly.

Homework

  • Create "Feedback" page on route "/feedback"
  • Try to create autoloadable JSON configuration file with TCP port and identifier "AppConfig"

Context

Function "run" returns Autoload Context - special entity which contains all autoloadable modules:

  • This context sends as first argument to each "boostrap" function of internal modules;
  • You can require any module founded in directories by it's "id" field value;
  • You can export context outside (or export result of some "getModule" call) via exports/module.exports.

At the next lesson we will create several Autoload Contexts and try to unite them in one.

⚠️ **GitHub.com Fallback** ⚠️