Skip to content

MVC web framework for Node.js designed to make Express easier to use.

License

Notifications You must be signed in to change notification settings

reecer62/roosevelt

 
 

Repository files navigation

Roosevelt MVC web framework

Build Status codecov npm

Roosevelt is a web application development framework based on Express that aims to be the easiest web framework on the Node.js stack to learn and use.

Some notable features:

  • Minimal boilerplate to get started. Teddy Roosevelt—the most badass President of all-time—curtailed the abuse of monopolists, so there's no way he would ever put up with all the indecipherable boilerplate common to other web frameworks.
  • Default directory structure is simple, but easily configured.
  • Concise default MVC architecture.
  • Uses Teddy HTML templates by default which are much easier to read and maintain than popular alternatives. Can be configured to use any templating system that supports Express.
  • LESS and UglifyJS preconfigured out of the box to intelligently minify your external facing CSS and JS files. Other preprocessors are supported via wrapper modules.
  • Built-in, easy to use interface to browserify bundling for frontend JS modularization using the Node.js module exports and require syntax.
  • Automatic server reloading when your backend code changes (via nodemon) and automatic browser reloading when your frontend code changes (via reload).
  • Automatic HTML validation in development mode of your post-server rendered HTML using a local instance of the Nu HTML Checker.

Teddy Roosevelt's facial hair is a curly brace.

Note: this is documentation for Roosevelt 0.14.x. If you need API documentation for a previous version of Roosevelt, look here.

Table of contents

Create and run a Roosevelt app

First you will need to install Node.js. Both the current and LTS version of Node.js are supported. It is recommended that you install using a Node.js version manager like nvm rather than the official installer, as a version manager will allow you to switch between multiple versions of Node.js easily.

Some important caveats to note:

The Java JDK is also required for development work. The JDK is required for the local HTML validator feature.

Once you have a sane development environment, you can proceed with the standard install procedure below.

Using the Roosevelt app generator

The Roosevelt app generator is a command line script based on Yeoman that can create a sample Roosevelt app for you.

To use it, first globally install Yeoman and the Yeoman-based Roosevelt app generator:

npm i -g yo generator-roosevelt

Create a Roosevelt app using the Roosevelt app generator:

yo roosevelt

Then follow the prompts.

Afterward, cd to your app's directory and install dependencies:

npm i

Run in development mode:

npm run d

Or run in production mode:

npm run p

Create a Roosevelt app manually

It is also possible to create a Roosevelt app without using the app generator. This will result in a more minimalist default configuration (e.g. no CSS or JS preprocessors enabled by default).

To do that:

  • First create a new folder and cd into it.

  • Then npm i roosevelt. This will create a node_modules folder with Roosevelt and its bare minimum dependencies.

  • Create a file named app.js.

  • Put this code in app.js:

    require('roosevelt')({
      'generateFolderStructure': true
    }).startServer()
  • Then node app.js. If the generateFolderStructure parameter is set to true like the above code example, an entire Roosevelt app with bare minimum viability will be created and the server will be started. See below for more information about parameter configuration.

Available npm scripts

Roosevelt apps created with the app generator come with the following notable npm scripts prepopulated in package.json:

  • npm run dev-install: Installs Roosevelt with its devDependencies to support running Roosevelt in development mode.
    • Default shorthands:
      • npm run di
    • Script is short for: cd ./node_modules/roosevelt && npm install --only=dev
  • npm run dev-prune: Removes Roosevelt's devDependencies to support deploying Roosevelt apps with smaller production builds. Note: can prevent being able to run Roosevelt in development mode.
    • Default shorthands:
      • npm run dp
    • Script is short for: cd ./node_modules/roosevelt && npm prune --production
  • npm run production: Runs the app in production mode.
    • Default shorthands:
      • npm run prod
      • npm run p
      • npm start
    • Script is short for: nodemon app.js --production-mode
  • npm run development: Runs the app in development mode.
    • Default shorthands:
      • npm run dev
      • npm run d
    • Script is short for: nodemon app.js --development-mode
  • npm run proddev: Runs the app in production mode, but with the public folder hosted by the Roosevelt app. This is useful for doing development in production mode without having to stage a complex simulation of your production environment, which would likely include hosting static files via another web server better-suited to serving statics like Apache or nginx.
    • Default shorthands:
      • npm run pd
    • Script is short for: nodemon app.js --host-public
  • npm run kill-validator: Finds the HTML validator process and kills it if it is running.
    • Default shorthand:
      • npm run kv
    • Script is short for: node ./node_modules/roosevelt/lib/scripts/killValidator.js
  • npm run clean: Removes all build artifacts (symlinks and directories) auto-generated by Roosevelt. Will prompt to confirm before deleting any files.
    • Default shorthand:
      • npm run c
    • Script is short for: node ./node_modules/roosevelt/lib/scripts/appCleanup.js
  • npm run config-audit: Scans current rooseveltConfig and scripts in package.json and warns about any parameters or npm scripts that don't match the current Roosevelt API:
    • Default shorthand:
      • npm run a
    • Script is short for: node ./node_modules/roosevelt/lib/scripts/configAuditor.js
    • Note: this will run automatically whenever you run npm i as well.

Available command line arguments

  • node app.js --production-mode: Runs the app in production mode.
    • Default shorthands:
      • --prod
      • -p
  • node app.js --development-mode: Runs the app in development mode.
    • Default shorthands:
      • --dev
      • -d
  • node app.js --cores <m>: Configures how many CPUs your app will run on.
    • <m> can be either a number representing the desired cores, or you can supply max to use all available CPUs.
      • Default is 1.
    • Default shorthand:
      • -c
  • node app.js --enable-validator: Forces the HTML validator to be enabled.
    • Default shorthands:
      • --html-validator
      • -h
  • node app.js --disable-validator: Forces the HTML validator to be disabled.
    • Default shorthands:
      • --raw
      • -r
  • node app.js --background-validator: Forces the HTML validator to run as a detached background process.
    • Default shorthand:
      • -b
  • node app.js --attach-validator: Forces the HTML validator to run as an attached process.
    • Default shorthand:
      • -a
  • node app.js --enable-validator-autokiller: Forces the HTML validator autokiller to be enabled.
    • Default shorthands:
      • --html-validator-autokiller
      • -k
  • node app.js --disable-validator-autokiller: Forces the HTML validator autokiller to be disabled.
    • Default shorthands:
      • --no-autokiller
      • -n
  • node app.js --host-public: Forces Roosevelt to always host the public folder even when alwaysHostPublic is set to false. Useful for testing production mode.
    • Default shorthands:
      • --statics
      • -s

Combining npm scripts and command line arguments

The npm scripts can be combined with the command line flags.

For example, running npm run d -- -r will run your app in development mode and force the HTML validator to be disabled.

Recognized environment variables

The following is a list of environment variables that Roosevelt listens for.

  • NODE_ENV:
    • Set to production to force the app into production mode.
    • Set to development to force the app into development mode.
  • NODE_PORT: Default HTTP port to run your app on.
  • HTTP_PORT: Default HTTP port to run your app on. Takes precedence over NODE_PORT.
  • HTTPS_PORT: Default HTTPS port to run your app on.
  • ROOSEVELT_VALIDATOR:
    • Set to detached to force the HTML validator to run as a detached background process.
    • Set to attached to force the HTML validator to run as an attached process.
  • ROOSEVELT_AUTOKILLER:
    • Set to on to spawn a process to kill the HTML validator if it is running in the background and idle for more than a certain amount of time. The timeout can be configured in app behavior parameters.
    • Set to offto disable the HTML validator autokiller.

Environment variable precedence:

Default directory structure

  • app.js: Entry point to your application. Feel free to rename this, but make sure to update package.json's reference to it.
  • mvc: Folder for models, views, and controllers. All configurable via parameters (see below).
    • controllers: Folder for controller files.
    • models: Folder for model files.
    • views: Folder for view files.
  • node_modules: A standard folder where all modules your app depends on (such as Roosevelt) are installed to. This folder is created by the npm i command.
  • package.json: A standard file in Node.js apps for configuring your app.
  • public: All contents within this folder will be exposed as static files.
  • statics: Folder for source CSS, image, JS, and other static files. By default some of the contents of this folder are symlinked to from public, which you can configure (see below).
    • css: Folder for source CSS files.
    • images: Folder for source image files.
    • js: Folder for source JS files.
  • .gitignore: A standard file which contains a list of files and folders to ignore if your project is in a git repo.

Default .gitignore

The default .gitignore file contains many common important things to ignore, however you may need to tweak it to your liking before committing a fresh Roosevelt app to your git repo.

Some notable things ignored by default and why:

  • public: It's recommended that you don't create files in this folder manually, but instead use the staticsSymlinksToPublic parameter detailed below to expose folders in your statics directory via auto-generated symlinks.
  • .build: By default Roosevelt will compile LESS and JS files down to minified versions in statics/.build when the server starts. As such, it's not recommended to place files in the build directory manually.
  • node_modules: This folder will be auto-generated when you run the npm i step to set up your app. Since some modules you might include later in your app can be platform-specific and are compiled for your OS during the install step, it's generally not recommended to commit the node_modules folder to git.

Configure your app with parameters

Roosevelt is designed to have a minimal amount of boilerplate so you can spend less time focused on configuration and more time writing your app. All parameters are optional. As such, by default, all that's in app.js is this:

require('roosevelt')().startServer();

Roosevelt will determine your app's name by examining "name" in package.json. If none is provided, it will use Roosevelt Express instead.

Also, while it is recommended that you pass parameters to Roosevelt via package.json under "rooseveltConfig", you can also pass parameters programmatically via Roosevelt's constructor like so:

require('roosevelt')({
  paramName: 'paramValue',
  param2:    'value2',
  etc:       'etc'
}).startServer();

This is particularly useful for setting parameters that can't be defined in package.json such as event handlers (see below).

In addition, all parameters support template literal style variables. For example:

{
  "port": 4000,
  "https": {
    "port": "${port + 1}"
  },
  "css": {
    "sourcePath": "css",
    "output": ".build/${css.sourcePath}",
  }
}

Resolves to:

{
  "port": 4000,
  "https": {
    "port": 4001
  },
  "css": {
    "sourcePath": "css",
    "output": ".build/css",
  }
}

App behavior parameters

  • port: The HTTP port your app will run on.

    • Default: [Number|String] 43711.
  • enableCLIFlags: Enables parsing of command line flags.

    • Default: [Boolean] true.
  • generateFolderStructure: When enabled Roosevelt will generate user specified directories (e.g. MVC parameters and statics parameters).

    • Default: [Boolean] true.
      • Exception to default: When package.json is not present or rooseveltConfig is not present in package.json, this parameter will be automatically set to false by default. This is a defensive measure to minimize the risk of files and folders being created in scenarios when they are not wanted.
    • This parameter is useful in scenarios when you want to create a Roosevelt app entirely from nothing (without using generator-roosevelt). See create a Roosevelt app manually for an example.
  • appDir: Root directory of your application.

    • Default: [String] The directory where your project package.json is located.
  • localhostOnly: Listen only to requests coming from localhost in production mode. This is useful in environments where it is expected that HTTP requests to your app will be proxied through a more traditional web server like Apache or nginx. This setting is ignored in development mode.

    • Default: [Boolean] true.
  • logging: Parameters to pass to roosevelt-logger. See roosevelt-logger parameters documentation for configuration options.

    • Default: [Object]

      {
        "methods": {
          "http": true,
          "info": true,
          "warn": true,
          "error": true,
          "verbose": false
        }
      }
    • You can also declare a custom log types and classify them as logs, warnings, or errors:

      • Default logging parameter with custom log type called debug added to it: [Object]

        {
          "http": true,
          "info": true,
          "warn": true,
          "verbose": false,
          "debug": {
            "enable": true,
            "type": "error"
          }
        }
        • enable parameter: Enables or disables the custom log.

          • Default: [Boolean] true.
        • type parameter: Specifies what kind of log your custom log is:

          • Allowed values: [String] info, warn, or error.
  • minify: Enables HTML minification as well as the minification step in supporting CSS and JS compilers.

    • Default: [Boolean] true.
    • Note: Automatically disabled during development mode.
  • htmlValidator: Parameters to send to html-validator:

    • enable: [Boolean] Enables or disables the built-in HTML validator.

      • Note: The validator is only available in development mode.
    • exceptions: Sending a custom request header can disable the validator on a per request basis. The name of this request header and model value can be customized with this parameter.

      • Default: [Object]

        "exceptions": {
          "requestHeader": "Partial",
          "modelValue": "_disableValidator"
        }
    • port: [Number] Port to spawn the validator process on.

    • separateProcess: [Object] How to run the validator:

      • enable: [Boolean] Run the validator as a detached background process.
      • autoKiller: [Boolean] Spawns a process to kill the validator if it is running in the background and idle for more than a certain amount of time.
      • autoKillerTimeout: [Number] Time (in milliseconds) that the validator auto-killer process waits before it kills the validator running in the background.
        • Note: You will see "GET /roosevelt-dev-mode-ping HTTP/1.1" 404 in your HTTP logs when autoKiller is enabled if you allow your app to idle in development mode. This is a normal behavior that the autokiller uses to determine if it should kill the validator process.
    • showWarnings: [Boolean] When set to true, shows HTML validation warnings in addition to errors.

    • Default: [Object]

      {
        "enable": true,
        "separateProcess": {
          "enable": true,
          "autoKiller": true,
          "autoKillerTimeout": 360000
        },
        "port": 48888,
        "exceptions": {
          "requestHeader": "Partial",
          "modelValue": "_disableValidator"
        },
        "showWarnings": true
      }
  • multipart: Settings to pass along to formidable using formidable's API for multipart form processing. Access files uploaded in your controllers by examining the req.files object. Roosevelt will remove any files uploaded to the uploadDir when the request ends automatically. To keep any, be sure to move them before the request ends. To disable multipart forms entirely, set this parameter to false.

    • Default: [Boolean]

      {
        "multiples": true
      }
  • toobusy: Parameters to pass to the node-toobusy module.

    • maxLagPerRequest: [Number] Maximum amount of time (in milliseconds) a given request is allowed to take before being interrupted with a 503 error.

    • lagCheckInterval: [Number] Interval (in milliseconds) for checking event loop lag in milliseconds.

    • Default: [Object]

      {
        "maxLagPerRequest": 70,
        "lagCheckInterval": 500,
      }
  • bodyParser: Parameters to supply to the body-parser module.

    • urlEncoded: [Object] Parameters to supply to body-parser.urlencoded.

    • json: [Object] Parameters to supply to body-parser.json.

    • Default: [Object]

      {
        "urlEncoded": {
          "extended": true
        },
        "json": {}
      }
  • checkDependencies: Whether or not to warn if dependencies are out of date.

    • Default: [Boolean] true.
  • cores: By default, Roosevelt will run on 1 CPU, but you can change the number of cores that the app will run on with this parameter.

    • Default: [Number] 1.
    • To use all available cores, set this value to max.
  • shutdownTimeout: Maximum amount of time in milliseconds given to Roosevelt to gracefully shut itself down when sent the kill signal.

    • Default: [Number] 30000 (30 seconds).

HTTPS parameters

  • https: [Object] Run a HTTPS server using Roosevelt.
    • Object members:
      • enable: Enable a HTTPS server.
        • Default: [Boolean] false.
      • force: Disallow unencrypted HTTP and route all traffic through HTTPS.
        • Default: [Boolean] false.
      • port: The port your app will run a HTTPS server on.
        • Default: [Number] 43733.
      • authInfoPath: [Object] Specify either the paths where the server certificate files can be found or set the appropriate parameters to be a PKCS#12-formatted string or certificate or key strings.
        • Default: undefined.
        • Object members:
          • p12: [Object] Parameter used when the server certificate/key is in PKCS#12 format.
            • Object members:
              • p12Path: [String] Either the path to a PKCS#12-formatted file (.p12/.pfx) or a PKCS#12-formatted string or buffer (i.e. the result of fs.readFileSync(/path/to/file/example.p12))
                • Default: undefined.
              • passphrase: [String] The password used to encrypt the PKCS#12-formatted file or string.
                • Default: undefined.
          • authCertAndKey: [Object] Parameter used when the server certificate and key are in separate PEM-encoded files.
            • Object members:
              • cert: [String] Either the path to a PEM-encoded certificate file (.crt, .cer, etc.) or a PEM-encoded certificate string.
                • Default: undefined.
              • key: [String] Either the path to a PEM-encoded key file (.crt, .cer, etc.) or a PEM-encoded key string for the certificate given in cert.
                • Default: undefined.
      • caCert: [String] Either the path to a PEM-encoded Certificate Authority root certificate or certificate chain or a PEM-encoded Certificate Authority root certificate or certificate chain string. This certificate (chain) will be used to verify client certificates presented to the server. It is only needed if requestCert and rejectUnauthorized are both set to true and the client certificates are not signed by a Certificate Authority in the default publicly trusted list of CAs curated by Mozilla.
        • Default: undefined.
      • requestCert: [Boolean] Set whether to request a certificate from the client attempting to connect to the server to verify the client's identity.
        • Default: undefined.
      • rejectUnauthorized: [Boolean] Set whether to reject connections from clients that do no present a valid certificate to the server. (Ignored if requestCert is set to false.)
        • Default: undefined.
      • Default: [Object] {}.

MVC parameters

  • modelsPath: Relative path on filesystem to where your model files are located.

    • Default: [String] "mvc/models".
  • viewsPath: Relative path on filesystem to where your view files are located.

    • Default: [String] "mvc/views".
  • viewEngine: What templating engine to use, formatted as "fileExtension: nodeModule".

    • generator-roosevelt default: [String] "html: teddy".

    • Also by default when using the generator, the module teddy is marked as a dependency in package.json.

    • Bare Roosevelt default (when an app is created without the generator): [String] none. Can also be set to null to use no templating engine.

    • To use multiple templating systems, supply an array of engines to use in the same string format. Each engine you use must also be marked as a dependency in your app's package.json. Whichever engine you supply first with this parameter will be considered the default.

    • Example configuration using multiple templating systems: [Object]

      {
        "viewEngine": [
          "html: teddy",
          "mustache: mustache",
          "handlebars: handlebars",
          "ejs: ejs"
        ]
      }
  • controllersPath: Relative path on filesystem to where your controller files are located.

    • Default: [String] "mvc/controllers".
  • errorPages: Relative path on filesystem to where your various error page controller files are located. If you do not supply them, Roosevelt will use its default ones instead:

  • routers: [Object] List of Express Routers to create for groups of controllers or static files. If none are defined, Roosevelt will default to creating one single global router with the route prefix / that all controllers and all static files will be routed through.

    • Object members:

      • controllers: [Array] List of Express Routers which can be used to (among other things) prefix a whole series of controller routes.

        • prefix: [String] The URL path prefix for the router to use.
        • files: [Array] List of files or directories in controllersPath that will be mounted to this route.
        • Default: [Boolean] false.
        • Note: controllers can also be a [String] that represents a schema file within the controllers directory. That file should define and export the list of Express Routers the same way as you would within the rooseveltConfig.
        • Example usage:
        [{
          "prefix": "/something",
          "files": ["controller.js", "directory"]
        }]
      • public: [Array] List of Express Routers which can be used to (among other things) prefix a whole series of static files into a series of public routes.

        • prefix: [String] The URL path prefix for the public directory to use.
        • dirs: [Array] List of directories in publicFolder that will be mounted to this route.
        • Default: [Boolean] false.
        • Example usage:
        [{
          "prefix": "/something",
          "dirs": ["css", "images", "js"]
        }]
    • Important limitation: When using routers to mount a sub application, it constrains the publicFolder of the sub app as follows:

      1. /paths inherit the path of the parent, changing http://domain/path to http://domain/parentApp/path, which will likely break the sub app's static assets hosted in the publicFolder if they are referenced that way.
      2. ./paths will generally still work because they are relative, but this is often not desired in production contexts.
      3. http://domain/absolutePaths will still work and is recommended if you want your app to be consumed as a sub app by another app.

Statics parameters

  • staticsRoot: Relative path on filesystem to where your source static assets are located. By default this folder will not be made public, but is instead meant to store unprocessed or uncompressed source assets that will later be preprocessed and exposed in public.

    • Default: [String] "statics".
  • htmlMinifier: How you want Roosevelt to minify your HTML:

    • enable: [Boolean] Enable HTML minification.

    • Note: Minification is automatically disabled in development mode.

    • exceptionRoutes: [Array] List of controller routes that will skip minification entirely. Set to false to minify all URLs.

    • options: [Object] Parameters to supply to html-minifier's API.

    • Default: [Object]

      {
        "enable": true,
        "exceptionRoutes": false,
        "options": {
          "removeComments": true,
          "collapseWhitespace": true,
          "collapseBooleanAttributes": true,
          "removeAttributeQuotes": true,
          "removeEmptyAttributes": true
        }
      }
  • css: [Object] How you want Roosevelt to configure your CSS preprocessor:

    • sourcePath: Subdirectory within staticsRoot where your CSS files are located. By default this folder will not be made public, but is instead meant to store unminified CSS source files which will be minified and written to a build directory when the app is started.

    • compiler: [Object] Which Roosevelt CSS preprocessor middleware (if any) to use.

      • nodeModule: [String] Node module name of the Roosevelt CSS preprocessor middleware you wish to use.

        • Note: Your chosen Roosevelt CSS preprocessor module must also be marked as a dependency in your app's package.json.
      • params: [Object] Parameters to send to the Roosevelt CSS preprocessor middleware if it accepts any.

      • cleanCSS: [Object] Roosevelt uses clean-css for CSS minification. Use the cleanCSS parameter to configure options passed to the constructor. See the clean-css docs for documentation on available parameters.

      • Note: The default preprocessor for a Roosevelt app created with generator-roosevelt is roosevelt-less, which is marked as a dependency in package.json on freshly generated Roosevelt apps. See roosevelt-less usage for details on what parameters are available.

      • The Roosevelt team also maintains roosevelt-sass, an alternative to roosevelt-less.

      • generator-roosevelt default configuration: [Object]

        {
          "nodeModule": "roosevelt-less",
          "params": {
            "cleanCSS": {},
            "sourceMap": null
          }
        }
      • Bare Roosevelt default (when an app is created without the generator): [String] none. Can also be set to null to use no CSS compiler.

    • whitelist: Array of CSS files to whitelist for compiling. Leave undefined to compile all files. Supply a : character after each file name to delimit an alternate file path and/or file name for the minified file.

      • Example array member: [String] less/example.less:.build/css/example.min.css (compiles less/example.less into .build/css/example.min.css).
    • output: Where to write compiled CSS files to. This folder will be symlinked into public by default.

    • symlinkToPublic: [Boolean] When enabled Roosevelt will automatically add your CSS directory to the staticsSymlinksToPublic parameter.

      • Note: If the compiler is enabled output will be symlinked. If not, sourcePath will be symlinked.
    • versionFile: If enabled, Roosevelt will create a CSS file which declares a CSS variable containing your app's version number from package.json. Enable this option by supplying an object with the member variables fileName and varName.

      • Default: null.

      • Example usage (with roosevelt-less): [Object]

        {
          "fileName": "_version.less",
          "varName": "appVersion"
        }
      • Assuming the default Roosevelt configuration otherwise, this will result in a file statics/css/_version.less with the following content:

        /* do not edit; generated automatically by Roosevelt */ @appVersion: '0.1.0';
      • Some things to note:

        • If there is already a file there with that name, this will overwrite it, so be careful!
        • It's generally a good idea to add this file to .gitignore, since it is a build artifact.
    • Default: [Object]

      {
        "sourcePath": "css",
        "compiler": {
          "nodeModule": "roosevelt-less",
          "params": {
            "cleanCSS": {},
            "sourceMap": null
          }
        },
        "whitelist": null,
        "output": ".build/css",
        "symlinkToPublic": true,
        "versionFile": null
      }
  • js: [Object] How you want Roosevelt to configure your JS compiled:

    • sourcePath: Subdirectory within staticsRoot where your JS files are located. By default this folder will not be made public, but is instead meant to store unminified JS source files which will be minified and written to a build directory when the app is started.

    • compiler: Which Roosevelt JS minifier middleware (if any) to use.

      • nodeModule: [String] Node module name of the Roosevelt JS minifier middleware you wish to use.

        • Note: Your chosen Roosevelt JS minifier module must also be marked as a dependency in your app's package.json.
      • showWarnings: [Boolean] Set to true to display compiler module warnings.

      • params: [Object] Parameters to send to the Roosevelt JS minifier middleware if it accepts any.

      • Note: The default minifier for a Roosevelt app created with generator-roosevelt is roosevelt-uglify, which is marked as a dependency in package.json on freshly generated Roosevelt apps. See roosevelt-uglify usage for details on what parameters are available.

        • The Roosevelt team also maintains roosevelt-closure, an alternative to roosevelt-uglify.
      • generator-roosevelt default configuration: [Object]

        {
          "nodeModule": "roosevelt-uglify",
          "showWarnings": false,
          "params": {}
        }
      • Bare Roosevelt default (when an app is created without the generator): [String] none. Can also be set to null to use no JS minifier.

    • whitelist: Array of JS files to whitelist for minification. Leave undefined to compile all files. Supply a : character after each file name to delimit an alternate file path and/or file name for the minified file.

      • Default: null (compiles all JS files, if a JS minifier is enabled).
      • Example array member: [String] library-name/example.js:lib/example.min.js (compiles library-name/example.js into lib/example.min.js).
    • blacklist: Array of JS files to exempt from minification. These files will be copied as-is to the build folder. Leave undefined to compile all files.

      • Default: null (compiles all JS files, if a JS minifier is enabled).
      • Example: [String] example.js.
    • output: Where to write compiled JS files to. This folder will be symlinked into public by default.

      • Default: [String] ".build/js".
    • symlinkToPublic: [Boolean] When enabled Roosevelt will automatically add your JS directory to the staticsSymlinksToPublic parameter.

      • Note: If the compiler is enabled output will be symlinked. If not, sourcePath will be symlinked.
    • bundler: Parameters related to bundling JS with browserify:

      • Note: Use of browserify in Roosevelt is optional. If no bundles are defined here, the browserify step will be skipped.

      • bundles: [Array] Declare one or more source JS files in your sourcePath to be browserify bundles via its bundle method.

        • env: [String] Bundle only in dev or prod mode. Omitting env will result in bundling in both modes.

        • params: [Object] The browserify parameters to send to browserify. If it is not set, these default parameters will be sent: {"paths": <your jsPath>}.

        • Examples: [Array] of [Objects]

          • Browserify bundle example declaring one bundle:

            [
              {
                "outputFile": "bundle.js",
                "files": [
                  "landingPage.js",
                  "main.js",
                  "etc.js"
                ],
                "params": {
                  "someOpt":
                  "someValue"
                }
              }
            ]
            • Browserify bundle example declaring one bundle only used in dev mode:

              [
                {
                  "outputFile": "bundle.js",
                  "env": "dev",
                  "files": [
                    "landingPage.js",
                    "main.js",
                    "etc.js"
                  ],
                  "params": {
                    "someOpt": "someValue"
                  }
                }
              ]
            • Browserify bundle example declaring multiple bundles:

              [
                {
                  "outputFile": "bundle1.js",
                  "files": [
                    "landingPage.js",
                    "main.js",
                    "etc.js"
                  ],
                  "params": {
                    "someOpt": "someValue"
                  }
                },
                {
                  "outputFile": "bundle2.js",
                  "files": [
                    "somethingElse.js",
                    "anotherThing.js",
                    "etc.js"
                  ]
                },
                etc...
              ]
        • Default: [Array] [].

      • output: Subdirectory within sourcePath where you would like browserify to deposit bundled JS files it produces.

        • Default: [String] ".bundled".
      • expose: Whether or not to copy the output directory to your build directory.

        • Default: [Boolean] true.
    • Default: [Object]

      {
        "sourcePath": "js",
        "compiler": {
          "nodeModule": "roosevelt-uglify",
          "showWarnings": false,
          "params": {}
        },
        "whitelist": null,
        "blacklist": null,
        "output": ".build/js",
        "symlinkToPublic": true,
        "bundler": {
          "bundles": [],
          "output": ".bundled",
          "expose": true
        }
      }
  • frontendReload: Settings to use for the reload module which automatically reloads your browser when your frontend code changes.

    • Default: [Object]

      {
        "enable": true,
        "port": 9856,
        "httpsPort": 9857,
        "verbose": false
      }
  • cleanTimer: Time in milliseconds to allow before considering files in CSS/JS compile directories stale and recommending running npm run clean.

    • Default: [Number] 604800000 (1 week)
    • Useful time conversions to milliseconds to configure this parameter with:
      • 1 day: 86400000.
      • 1 week: 604800000.
      • 1 month: 2419200000.
    • Set to 0, null, or anything that isn't a number to disable the check entirely.
  • clientViews: [Object] Allows you to expose view code to frontend JS for client-side templating.

    • exposeAll: [Boolean] Option to expose all templates. This will exclude templates that have <!-- roosevelt-blacklist --> at the top of the file or those listed in the blacklist property of clientViews.

      • Default: [Boolean] false.
    • blacklist: [Array] of [Strings] List of files or folders excluded when exposeAll is on.

      • Default: [Array] of [Strings] [].
      • Note: Anything that is in the blacklist or that has a <!-- roosevelt-blacklist --> tag will never be added to any whitelist.
    • whitelist: [Object] List of JS files to create mapped to which view files to expose.

      • Default: [Object] of [Arrays] {}.

      • Example:

          {
          "mainLayouts.js": ["baseLayout.html", "footer.html"],
            "forms.js": ["forms/formTemplate.html"]
        }
    • defaultBundle: [String] File name for the default location of templates if not specified with the <!-- roosevelt-whitelist <filepath> --> tag at the top of any template.

      • Default: [String] "bundle.js".
    • output: [String] Subdirectory within staticsRoot to define where to save the view JS bundles.

    • Default: [String] ".build/templates".

    • minify: [Boolean] Option to minify templates that are exposed via this feature.

    • Default: [Boolean] true.

    • minifyOptions: [Object] Parameters to supply to html-minifier's API.

    • Uses the params you set in htmlMinifier.options if empty.

  • Default: [Object]

        "clientViews": {
          "exposeAll": false,
          "blacklist": [],
          "whitelist": {},
          "defaultBundle": "bundle.js",
          "output": ".build/templates",
          "minify": true,
          "minifyOptions": {}
        }

Public folder parameters

  • publicFolder: All files and folders in this directory will be exposed as static files.

    • Default: [String] "public".
  • favicon: Location of your favicon file.

    • generator-roosevelt default: [String] "images/favicon.ico".
    • Bare Roosevelt default (when an app is created without the generator): [String] none. Can also be set to null to use no favicon.
  • staticsSymlinksToPublic: Array of folders from staticsRoot to make symlinks to in your public folder, formatted as either "linkName: linkTarget" (whitespace optional) or simply "linkName" if the link target has the same name as the desired link name.

    • Default: [Array] of [Strings]

      [
        "css: .build/css",
        "images",
        "js: .build/js"
      ]
  • versionedPublic: If set to true, Roosevelt will prepend your app's version number from package.json to your public folder. Versioning your public folder is useful for resetting your users' browser cache when you release a new version.

    • Default: [Boolean] false.
  • alwaysHostPublic: By default in production mode Roosevelt will not expose the public folder. It's recommended instead that you host the public folder yourself directly through another web server, such as Apache or nginx. However, if you wish to override this behavior and have Roosevelt host your public folder even in production mode, then set this setting to true.

    • Default: [Boolean] false.

Events

Roosevelt provides a series of events you can attach code to by passing a function to the desired event as a parameter to Roosevelt's constructor like so:

require('roosevelt')({
  onServerStart: (app) => { /* do something */ }
});

Event list

  • onServerInit(app): Fired when the server begins starting, prior to any actions taken by Roosevelt. Note: the multipart, routes, and roosevelt:state Express variables exposed by Roosevelt are not available yet during this event.
  • onServerStart(app): Fired when the server starts.
  • onReqStart(req, res, next): Fired at the beginning of each new request.
    • req: The request object created by Express.
    • res: The response object created by Express.
    • next: Callback to continue with the request. Must be called to continue the request.
  • onReqBeforeRoute(req, res, next): Fired just before executing the controller.
    • req: The request object created by Express.
    • res: The response object created by Express.
    • next: Callback to continue with the request. Must be called to continue the request.
  • onReqAfterRoute(req, res): Fired after the request ends.
  • onClientViewsProcess(template): Fired to preprocess templates before being exposed to the client
    • template: A string containing a template written in any templating engine (Teddy, Pug, Handlebars, etc)

Making controller files

Controller files are places to write Express routes. A route is the term Express uses for URL endpoints, such as http://yoursite/blog or http://yoursite/about.

To make a new controller, make a new file in the controllers directory. For example:

module.exports = (router, app) => { // router is an Express router and app is the Express app created by Roosevelt

  // standard Express route
  router.route('/about').get((req, res) => {

    // load a data model
    let model = require('models/dataModel');

    // render a Teddy template and pass it the model
    res.render('about', model);
  });
};

Note: If custom routers are being used, the res.redirect() method will prepend the prefix to redirects that are relative to the hostname. To override this setting pass true as the last argument.

Sometimes it is also useful to separate controller logic from your routing. This can be done by creating a reusable controller module.

An example would be creating a reusable controller for "404 Not Found" pages:

// reusable controller "notFound.js"
module.exports = (app, req, res) => {
  let model = { content: 'Cannot find this page' };
  res.status(404);
  res.render('404', model);
}

Reusable controller modules differ from standard controller modules in that they accept req and res arguments in addition to app. They are meant to be called from within routes rather than define new routes.

This allows them to be called at will in any other controller's route when needed:

// import the "notFound" controller logic previously defined
const throw404 = require('controllers/notFound');

module.exports = (router, app) => {
  router.route('/whatever').get((req, res) => {

    // test some logic that could fail
    // thus triggering the need for the 404 controller
    if (something) {

      // logic didn't fail
      // so render the page normally
      let model = require('models/dataModel');
      res.render('whatever', model);
    }
    else {

      // logic failed
      // so throw the 404 by executing your reusable controller
      throw404(app, req, res);
    }
  });
};

Making model files

Since the above example requires a model file named dataModel, you will need to make that too. To do that, place a file named dataModel.js in mvc/models.

Here's a simple example dataModel.js data model:

module.exports = {some: 'data'};

Making view files

Views by default are Teddy templates. See the Teddy documentation for information about how to author Teddy templates.

You can also use different templating engines by tweaking Roosevelt's MVC parameters.

Express variables exposed by Roosevelt

Roosevelt supplies several variables to Express that you may find handy. Access them using app.get('variableName').

Express variable Description
express The Express module.
routes List of all routes loaded in the Express app by Roosevelt.
viewEngine e.g. teddy by default Any view engine(s) you define will be exposed as an Express variable. For instance, the default view engine is teddy. So by default app.get('teddy') will return the teddy module.
view engine Default view engine file extension, e.g. .html.
formidable The formidable module Roosevelt uses internally. Used for handling multipart forms.
morgan The morgan module Roosevelt uses internally. HTTP request logger middleware.
logger The roosevelt-logger module Roosevelt uses internally. Used for console logging.
modelsPath Full path on the file system to where your app's models folder is located.
viewsPath or views Full path on the file system to where your app's views folder is located.
controllersPath Full path on the file system to where your app's controllers folder is located.
clientViewsBundledOutput Full path on the file system to where your app's client exposed views folder is located
staticsRoot Full path on the file system to where your app's statics folder is located.
publicFolder Full path on the file system to where your app's public folder is located.
cssPath Full path on the file system to where your app's CSS source files are located.
jsPath Full path on the file system to where your app's JS source files are located.
cssCompiledOutput Full path on the file system to where your app's minified CSS files are located.
jsCompiledOutput Full path on the file system to where your app's minified JS files are located.
jsBundledOutput Full path on the file system to where your app's bundled JS files are located.
env Either development or production.
params The parameters you sent to Roosevelt.
flags Command line flags sent to Roosevelt.
appDir The directory the main module is in.
appName The name of your app derived from package.json. Uses "Roosevelt Express" if no name is supplied.
appVersion The version number of your app derived from package.json.
package The contents of package.json.
roosevelt:state Application state, e.g. disconnecting if the app is currently being shut down.

Additionally the Roosevelt constructor returns the following object:

Roosevelt object members Description
expressApp [Object] The Express app created by Roosevelt.
httpServer [Object] The http server created by Roosevelt. httpServer is also available as a direct child of app, e.g. app.httpServer.
httpsServer [Object] The https server created by Roosevelt. httpsServer is also available as a direct child of app, e.g. app.httpsServer.
initServer [Method] Starts the HTML validator, sets up some middleware, runs the CSS and JS preprocessors, and maps routes, but does not start the HTTP server. Call this method manually first instead of startServer if you need to setup the Express app, but still need to do additional setup before the HTTP server is started. This method is automatically called by startServer once per instance if it has not yet already been called.
startServer [Method] Calls the listen method of http, https, or both (depending on your configuration) to start the web server with Roosevelt's config.
stopServer [Method] Stops the server and takes an optional argument stopServer('close') which stops the server from accepting new connections before exiting.

Express middleware and other configurations automatically loaded by Roosevelt

In addition to exposing a number of variables to Express and providing the MVC interface outlined above, Roosevelt also:

  • Includes the compression middleware.
  • Includes the cookie-parser middleware.
  • Disables x-powered-by and etag.
  • Logs HTTP requests to the console using morgan, specifically morgan('combined').
  • Includes the method-override middleware.

Deployment

Removing dependencies unneeded in production

In contexts where you only need to run Roosevelt in production mode, you can remove some dependencies that are only needed in development mode in order to shrink the footprint of production builds.

The biggest development mode-only dependency you can remove is vnu-jar. To remove it, run npm rm vnu-jar --no-save.

The complete list of Roosevelt dependencies that are only needed in development mode is:

  • fkill
  • html-validator
  • prismjs
  • ps-node
  • reload
  • tmp
  • vnu-jar

To remove them all, run npm rm fkill html-validator prismjs ps-node reload tmp vnu-jar --no-save.

Be sure none of those dependencies are needed elsewhere in your app first.

Authoring your own CSS and JS preprocessors

There are two ways to replace Roosevelt's default CSS and JS preprocessors with another one.

The first way is to swap out the default roosevelt-less CSS preprocessor module or roosevelt-uglify JS preprocessor module for something else, e.g. roosevelt-sass, roosevelt-closure, or a custom module that you've created.

You can also define your own preprocessors on the fly at start time in Roosevelt's constructor like so:

let app = require('roosevelt')({
  cssCompiler: app => {
    return {
      versionCode: app => {
        // write code to return the version of your app here
      },
      parse: (app, fileName) => {
        // write code to preprocess CSS here
      }
    }
  },
  jsCompiler: app => {
    return {
      parse: (app, fileName) => {
        // write code to preprocess JS here
      }
    }
  }
})

API:

  • cssCompiler(app): Custom CSS preprocessor.
    • versionCode(app): Function to return the version of your app.
    • parse(app, fileName): Function to preprocess CSS.
      • app: The Express app created by Roosevelt.
      • fileName: Name of file to compile.
  • jsCompiler(app): Custom JavaScript preprocessor.
    • parse(app, fileName): Function to preprocess JavaScript.
      • app: The Express app created by Roosevelt.
      • fileName: Name of file to compile.

Lastly, in order to activate the custom preprocessor feature, alter package.json to declare the compiler nodeModule to be custom:

"css": {
  "compiler": {
    "nodeModule": "custom",
  [...]
"js": {
  "compiler": {
    "nodeModule": "custom",
  [...]

Documentation for previous versions of Roosevelt

About

MVC web framework for Node.js designed to make Express easier to use.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 98.7%
  • HTML 1.3%