Giter Site home page Giter Site logo

express-load's Introduction

Express Load

NOTE:

The successor to this module is here: consign it's not express specific and is lighter in weight. Check it out :)

The express-load module provides the ability to load scripts into an Express instance from specified directories or files. Make large express MVC applications easier to develop by allowing a logical file separation without having to require your scripts. See the examples folder for information.

Express Load can be used to autoload models, routes, schemas, configs, controllers, object maps... etc...

You get access to the autoloaded files in the Express application instance to keep out of the global namespace. This also allows access to the scripts via the request object. req.app

A script at controllers/user.js becomes available as app.controllers.user or req.app.controllers.user in a request.

Installation

$ npm install express-load

Usage

var load = require('express-load');

load('config')
  .then('routes')
  .into(app);

Simple Express Load Example

controllers/site.js

exports.index = function(req, res, next) {
  res.send('Hello world!');
};

routes/site.js

module.exports = function(app) {

  var site = app.controllers.site;
  
  app.get('/',
    site.index
  );

};

app.js

var express = require('express')
  , load = require('express-load');

var app = express();

load('controllers')
  .then('routes')
  .into(app);

app.listen(3000)

Load Order

The basic load order is the order that is specified in code, for example, you will want to load models before controllers and controllers before routes:

load('models')
  .then('controllers')
  .then('routes')
  .into(app);

This would simply load all models, all controllers, all routes in that order (alphabetical order within the directories).

Specifying Complex Order

If you have two files in the foo folder a.js and z.js and you need z.js loaded BEFORE a.js you would simply do the following:

load('foo/z.js').then('foo').into(app);

express-load will recognise the order and will not add it again later down the chain.

Async load

If you have an async script to load, express-load will pass a callback function to your script and wait this function be called to load remain scripts.

load('syncFoo.js').then('asyncBar.js').then('syncBar.js');

// asyncBar.js
module.exports = function (app, callback) {
    setTimeout(function () {
        console.log('After 5 seconds');
        callback();
    }, 5000);
};

If you need to know when async load is complete, you may pass the callback function as a second argument to into. The callback get called when async load is completed.

load('models')
    .then('collections')
    .then('controllers')
    .into(app, function(err, instance) {
        if(err) throw err;
        app.listen(app.get('port'));
    });

Logging

Logging is off by default but can be enabled in the following way:

load('controllers', {verbose:true}).into(app);

See the verbose example in the examples folder.

Files and folders

express-load will ignore hidden files and folders (by leading period) unless you explicitly define them to be loaded.

express-load will by default only load files ending with .js, .node, .coffee, .sjs, .json extensions, unless you set checkext option to false : no file extension check at all. You can also change the list of allowed extension (in extlist option).

load('controllers', {checkext:true, extlist:['.js','.myextension']}).into(app);

Nested Folders

If you had nested folders like the following example:

models
	humans
		cool.js
		not.js
	animals
		dog.js
		cat.js

You would end up with the scripts being available in the following structure:

app.models.humans.cool
app.models.humans.not
app.models.animals.dog
app.models.animals.cat

Base directory

Express-load load scripts based on relative directory, however you can use cwd option if you want to load based on the other directory. see example.

Getting the Express Application instance

This can be done in one of two ways:

In a script that is auto-loaded...

module.exports = function(app) {
  console.log(app);
};

A script will only be loaded with parameters if module.exports is a function. Multiple parameters can be passed to the script in the into method, for example:

load('controllers').into(app, parameter, another);

From a request object...

app.get('/', function(req, res, next) {
  console.log(req.app);
});

File and Folder names vs Object namespace examples

The names of files and folders are used to create the namespace therefore rules have been put in place. dashes - and periods . are removed and the following character is uppercased. For example:

some-controllers/my.controller.js -> *.someControllers.myController

Please see the examples folder for working examples of express-load in action.

License

(The MIT License)

Copyright (c) 2012 Jarrad Seers <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

express-load's People

Contributors

coconitro avatar cuongthamhl avatar e7h4n avatar fabien avatar jarradseers avatar jmbarbier avatar myanimal avatar popomore avatar printercu avatar reaktivo avatar rodolfosilva avatar sgarbesi avatar victorsenam avatar vkadam avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

express-load's Issues

Is there a way to ignore a parent directory?

For my folder structure, I have my models, views, controllers, and routes in a folder called app:
app/controllers/.js
app/models/
.js
app/routes/.js
app/views/

express-load loads everything with app. in the name:
app.app.controllers.*
app.app.models.*
app.app.routes.*

Can there be a setting to ignore a specific base dir, for example:
{basedir: 'app'}

would strip app from the beginning so that it would result in:
app.controllers.*
app.models.*
app.routes.*

I know I could just move the controllers/models/routes into the base dir, but I would prefer to organize my project, and reduce the base dir clutter.

Edit: To add - I was previously running my code on node 0.6, and I modified express-load from "fs.existsSync" to "path.existsSync"
I started using node 0.8, and downloaded an unmodified express-load when this problem started to occur.

load js file in a specific path

i have an app directory looks like

app/
├── controllers
│   ├── index.js
│   └── users.js
├── errors.js
├── models
│   └── user.js
└── other_things

in the server.js i have the following code using express-load

load('errors', {cwd: 'app'})
  .then('models')
  .then('controllers')
  .into(app);

but console.log(app.errors); is undefined
and console.log(app); show the following among many other unrelated output
'': { errors: { not_found: [Function] } } }

how do i convert that to be loaded like
'errors':{ not_found: [Function] } }

the errors.js is defined as following

exports.not_found = function(err){
  //... yada yada...
}

Nested folder issue

Imagine you have the following directory structure:

app
+++ controller
+++ model
+++ view

Now by using load('app/controller').into(app); I have to type app.app.controller.

It would be nice if we could change the "app object" and simplify the way how to access subfolders. i.e. load('app/controller', {name: 'controller'}).into(app);

Help me "not access because it does not exist"

folder: models/user.js
controllers/user.js

app.js

var express = require('express'), load = require('express-load');
var app = express();

load('models')
  .then('controllers')
  .into(app);

but

models/user.js
module.exports = function(app) {
console.log(app.controllers); // not work?
}

Can not access because it does not exist

Nesting directories/files

I have a folder/file structure like this:

controller/
  app/
    token.js
    token/
      access.js
      authorization.js
      refresh.js

It would be nice to be able to extend off of app allowing to have multiple levels. I can't seem to get it working and didn't see anything in the documentation explaining this.

Example:

controller.app.token();
controller.app.token.access(); // This doesn't work.

TypeError: Arguments to path.join must be strings

Hello, i have the following error

TypeError: Arguments to path.join must be strings
      at Object.posix.join (path.js:467:13)
      at Context.<anonymous> (test/rank/rankServiceTest.js:19:3)

with the following code

var Q = require('q');
var async = require('async');
var expect = require('expect.js');
var load = require('express-load');
var app = require('../../app.js');
var mongoose = require('mongoose');
var basicMongoDbMock = require('../mockDb/basicMongoDbMock');

describe('Suite 01', function () {

    before(function (done) {
        this.timeout(8000);

        load('config') //  at Context.<anonymous> (test/rank/rankServiceTest.js:19:3)
            .then('enums')
            .then('models/UniqueId.js')
            .then('models')
            .then('modules/rank')
            .into(app, function () {
            });
    });

    beforeEach(function (done) {
        mongoose.connect('mongodb://localhost:27017/squid_test');

        basicMongoDbMock
            .seed(Mission, Participation, User, Image)
            .then(function () {
                done();
            });
    });

    afterEach(function (done) {
        basicMongoDbMock
            .unseed(Mission, Participation, User, Image)
            .then(function () {
                mongoose.disconnect(function () {
                    done();
                });
            });
    });

    it('Should...', function (done) {

    });

});

This is the start line of the exception

        load('config') //  at Context.<anonymous> (test/rank/rankServiceTest.js:19:3)

Have any idea of the cause for the error?

filename with '-' character

Hi,

Do you think it will be possible to load js files which contains '-' in names.

'myfile-name.js' for instance ?

and to retrieve it then by app.controler['myfile-name']

Support for regular expression in extlist.

We have a folder structure where we store test files under src like
app
--test
----app_spec.js
app.js

In this scenario I can use regular expression to match all *.js but not *_spec.js

help travis tests and path

Hi,

Here my tests case, I have developped https://github.com/darul75/express-json-refiner.

Last version on npm is ok but current has the following issue.

On local it works but on Travis it fails systematicaly and make me crazy.

I use mocha for making test, on root of project I use something like

mocha test/test.spec.js

2 directories in test/model and test/access are loaded by your module in this order as in access files I get reference to some model file.

normally content are retrieved in app.model and app.access but I got some suspiscion that namepace build on travis side is something like app.test.model and app.test.access...

could you help me and fork this project to look what is wrong.

https://travis-ci.org/darul75/express-json-refiner

thx,

julien

cwd option for "then" functions

Hi @jarradseers,
What do you think about loading cwd option from all the items? To me, it seems more intuitive.

load('models', {cwd: 'app'})
  .then('controllers', {cwd: 'app'})
  .then('routes', {cwd: 'config'})
  .into(app)

Do you think it makes sense?

Today load() sets the cwd param to all modules.

Express Router with express load

Hi all,

I'd like to know, if there is a manner to add a fixed prefix for routes using express load.

For example, today with express Router, I can do the following:

var router = express.Router();
var user = require('./app/services/user');
router.route('/users').get(user.list);
app.use('/api/v1/', router);

So, all my requests path will attend on: /api/v1/users or whatever is the route that I declare on router.route.

Can I do something like it with express-load?

Thanks a lot!

[]'s
Natan Deitch

Object .js,.node,.json,.coffee,.sjs has no method 'test'

Hi,

I'm using your library:

load('config')
.then('mongoose')
.then('models')
.then('controllers')
.then('routes')
.into('app');

And receiving an error:
Object .js,.node,.json,.coffee,.sjs has no method 'test'

Windows 7, Node v0.10.25

How to stop sub-modules load?

Hi, Is there a way to only load modules, avoiding the load of sub-modules?

For example, I have a folder modules, with a lot of scripts to load, but there is only one module which need to load your own sub-modules using require, and I'd like to avoid the load of theses submodules.

Consideration

Hi @jarradseers

Just to letting you know that things get ugly (specially on post/delete/put requests) when you load your routes before the app.use(express.bodyParser()); Express can't parse the request properly when you load your routes before it. If you make a simple POST to a route which had been declared before bodyParser the req.params is completely empty.

It looks more like a express problem then a express-load problem but.... maybe you could do something under the hood that loads our routes on the right "timing".

how about support auto script reload?

in development i will change express scripts very frequently,but express-load can not auto reload the script when it's already been loaded. so why not support auto reload scripts?
by the way, the cwd is very useful for me

Problam with Files in folders

Hello everybody

I would like to know how to split the control methods into files. When I do controllers/users/index.js the following happens:

Error: Route.get() requires callback functions but got a [object Object]

controllers/users/index.js

module.exports = (app) => {
  var User = app.models.user
  return {
    index(req, res) {...}
  }
}

Thanks a lot!

[]'s

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.