gracenode

Framework for node.js to boostrap other node.js modules for easy use and uniformed synchronus setup.

gracenode 2.0

©Nobuyori Takahashi < voltrue2@yahoo.com >

  • Manages cluster process.

  • Handles daemonizing of the application and auto-restarting on file changes. Read here.

  • Bootstrap other modules to organize setting up of each module on starting of the application process. Read here.

  • Provides a built-in logging module. Read here.

  • Provides plethora of utility functions to aid development. Read here.

  • Provides HTTP router for web applications. Read here.

  • Provides fast template enigne. Read here.

NOTE: If you are running your application as a daemon with older version of gracenode, please make sure to stop the daemon before installing the newer version.

npm install gracenode

To install gracenode you can either add it to your package.json like so:

Install From Git Repository

{
    "dependencies": {
        "gracenode": "git+https://github.com/voltrue2/gracenode.git#master"
    }
}

Install From npm Repositiory

{
    "dependeicies": {
        "gracenode": "2.1.2"
    }
}

Install From Git Without package.json

npm install git+https://github.com/voltrue2/gracenode.git#master

In order to use gracenode, you need to properly set it up in your application root file (The file that starts your application).

To create a basic setup for your application, execute the following command from the root of your application directory:

./node_modules/gracenode/bin/boilerplate

The above command will create a very basic setup for you.

To start your own HTTP server from here on, execute make start.

The above command will daemonize your appliction and the daemon process will automatically restart if you change the application code or/and configurations.

NOTE: By default, your HTTP server will be listening to port http://localhost:8888.

If you executed ./node_modules/gracenode/bin/boilerplate, you now have Makefile in your application directory.

The following commands are now available:

  • Lint Your Javascript Files: make lint

You may add more direcotries to lint in Makefile to lint additional files.

  • Start Application: make start

  • Stop Application: make stop

  • Restart Application: make restart

  • Check Process Status: make status

  • Reload Application: make reload

The configuration file(s) are located in configs/.

There is a symbolic link that points to configs/config.json.

This is the file that the application is reading from.

To add more HTTP REST endpoints, add more routes to api/index.js.

You also need to create a route handler for the route(s) that you are adding.

Example:

gn.router.get('/hello2', require('./controllers/hello2'));

To add more views, you must add new views to api/views/index.js.

You also need to add a view handler for your new view.

Example:

modules.exports = {
hello: require('./hello'),
hello2: require('./hello2')
};

In order to add more templates, you need to add template files to templates/.

The added template files must be read in your new view handlers.

See the example in api/views/hello/index.js.

These are optional configurations, but you will want to know what they do.

var gn = require('gracenode');
 
// Here the configurations are given as an object 
gn.configure({
lint: {
// lint all application js files when starting. default is true 
enable: true,
// a list of file names or file paths to ignore linting. default is empty 
ignore: [],
// if this is set to true, lint error(s) will cause your application to terminate immediately. default is false 
strict: false
log: {
// default is false 
console: false,
// default is false 
color: false,
// default is undefined 
file: '/path/to/my/logging/dir/'
},
cluster: {
// Maximum number of workers. default is 0 
max: 0
},
router: {
// you must have this value if you need to use gracenode.router 
port: 8888,
// you must have this value if you need to use gracenode.router 
host: 'localhost'
},
render: {
// in order to use gracenode.render, you must provide this vakue 
path: '/path/to/templates/',
// custom cache size for render engine. it is an option 
cacheSize: 5000000
}
});
 
// Now start gracenode 
gn.start(function () {
// Your application is now ready! 
});
 

NOTE 1: You may give the configurations as a JSON file also:

gn.config(require('/path/to/my/config.json'));

NOTE 2: You may call .config() as many times a syou need to merge the configuration objects.

This is useful when you have shared common configurtions with other developers and your custom configrations for each.

gn.config(require('/path/to/my/shared/config.json'));
gn.config(require('/path/to/my/custom/config.json'));

NOTE 3: More details for logging and cluster configurations will be given later in this README.

gracenode lints your application code when gracenode.start() is called.

If gracenode detects a lint error, gracenode does not terminate immediately.

If, however, lint: { strict: true } is set, gracenode will terminate its process immediately on lint error(s).

NOTE: Uses jshint with the configurations below:

"jshintConfig": {
                "node": true,
                "bitwise": false,
                "camelcase": true,
                "curly": true,
                "eqeqeq": true,
                "forin": false,
                "immed": true,
                "latedef": false,
                "newcap": true,
                "noarg": true,
                "noempty": true,
                "undef": true,
                "unused": true,
                "nonew": true,
                "white": true,
                "maxdepth": 5,
                "quotmark": "single",
                "globals": {
                        "mocha": false,
                        "describe": false,
                        "it": false,
                        "before": false,
                        "beforeEach": false,
                        "after": false,
                        "afterEach": false
                }
        }

If strict mode is set to true, your application process will terminates on start if lint error(s) is detected.

This is set to false by default.

Example:

{
lint: {
enable: true,
strict: true
}
}

To disable gracenode liniting, add the following configuration to your application config.

lint: {
enable: false
}

You may have gracenode ignore certain files/directories for liniting by adding the following in your application configuration:

lint: {
ignore: [
''
]
}

In order to change lint configurations, add/change the following in your package.json:

"jshintConfig": {
                "node": true,
                "bitwise": false,
                "camelcase": true,
                "curly": true,
                "eqeqeq": true,
                "forin": false,
                "immed": true,
                "latedef": false,
                "newcap": true,
                "noarg": true,
                "noempty": true,
                "undef": true,
                "unused": true,
                "nonew": true,
                "white": true,
                "maxdepth": 5,
                "quotmark": "single",
                "globals": {
                        "mocha": false,
                        "describe": false,
                        "it": false,
                        "before": false,
                        "beforeEach": false,
                        "after": false,
                        "afterEach": false
                }
        }

There are 2 different ways to start your application as a daemon.

Assuming app.js is your appliction file to execute.

node app.js start -l /path/to/my/daemon/logging/

gracenode creates ./gracenode executable when you install gracenode.

Assuming app.js is your appliction file to execute.

./gracenode app.js start -l /path/to/my/daemon/logging/

NOTE: More details on the daemonization command options will be explain later in this README.

It is very useful when you are developing your application to automatically restart the running daemon on changes that your make.

To do so, you need to use a daemon command option -w.

node app.js start -l /path/to/my/daemon/logging/ -w /path/to/my/app/code/ /path/to/my/another/ap/code

NOTE: -w option watches the directories/files that are given and when there changes such as adding a new file, removing some files, and changing the existing file are detected, daemon will automatically restart so that your changes are now in effect without having to manually restart your daemon.

Some modules require some setting up before they can be used in your code, some setup process maybe asynchronous and your application has to wait for it to complete its process. When you use such modules, simply calling var mod = require('great-mod'); is not good enough especially when the module requires asynchronous setup.

gracenode can bootstrap all of these modules and handle setting up of each module in an organized way.

For example, assuming this foo module needs to read some files before it is ready, gracenode can handle it like so:

var gn = require('gracenode');
 
gn.use('foo', 'node_modules/foo', {
setupfunction (cb) {
this.readFromFiles(cb);
}
});
 
gn.start({
// Now gracenode is ready 
// And foo is also ready 
// To access foo module: 
gn.mod.foo.doSomething();
});

NOTE 1: The 2nd argument of .use() is a relative path to load the module foo. The path is relative to the root path of your application.

NOTE 2: The 3rd argument is an optional object that you can assign specific functions to perform setting and/or cleaning.

NOTE 3: this inside of the functions you assign to the 3rd argument is the module you are "using". In this example, this is foo module.

NOTE 4: More details on .use() and its options will be explained later in this README.

gracenode has a property .mod that holds all bootrstapped modules. The first argument of .use() will be the name of bootstrapped module.

Here is how you would access the bootstrapped modules in your application code:

var gn = require('gracenode');
 
gn.use('myModule', '/path/to/my/module/');
 
gn.start(function () {
gn.mod.myModule.doSomething();
});

gracenode can be used along side with express.

It will give your express application the support for clustering and daemoning out-of-the-box.

Example:

var gn = require('gracenode');
 
gn.use('express', require('express'));
 
gn.start(function () {
// start your express application 
var app = gn.mod.express();
app.listen(8000);
});

Logging module. For more details, please read here.

Library of built-in utility functions. For more details: here.

Dynamic renderer for HTML and other contents to be served from the server.

For more details, please read here.

Example:

gracenode.router.get('/', function (reqres) {
var data = {
title: 'Hello World'
};
var renderedHTML = gracenode.render('view/index.html', data); 
res.html(renderedHTML);
});

An HTTP server router to help you build HTTP rest server.

For more details please read here.

To register HTTP endpoints, call the following functions.

gracenode.config({
router: {
port: <number>,
host: <string>
}
});

Registers a routing for GET requests.

Example:

var gn = require('gracenode');
gn.config({
router: {
port: 8888,
host: 'localhost'
}
});
gn.router.get('/example', function (reqres) {
res.json({ title: 'Hello World' });
});
gn.router.get('/mypage', require('/path/to/mypage/handler'));

More Details Here

Returns a application root path as a string.

Set configurations as an object as an option.

This function can be called multiple times and it will merge all configuration objects being passed.

NOTE: The same configuration properties will be overwritten.

Returns a matching configurations.

Example:

var gn = require('gracenode');
gn.config({
log: {
file: '/path/to/log/dir/'
}
});
var logFilePath = gn.getConfig('log.file');

Assigns a function to be executed on uncaughtException event.

Assigns a function to be executed on process exit of gracenode. The assigned function will have a callback function passed.

Example:

gracenode.onExit(function (callback) {
// do something before terminating the process 
callback();
});

gracenode.require() requires a module from application root path.

Example:

// application root: /var/www/myapp/ 
// module path: /var/www/my/myapp/mystuff/ 
// required location: /var/www/myapp/look/here/index.js 
// without gracenode.require() 
var mystuff = require('../../mystuff');
// with gracenode.require() 
var mystuff = gracenode.require('mystuff');

gracenode can be configured with the following properties by default:

{
log: {
rotationType: [string],
useTimestamp: [boolean],
bufferSize: [int],
bufferFlushInterval: [int],
oneFile: [boolean],
file: [string],
console: [boolean],
remote: [object],
color: [boolean],
showHidden: [boolean],
depth: [int],
level: [string]
},
cluster: {
max: [int],
autoSpawn: [boolean],
sync: [boolean]
}
}

NOTE: To use configurations for bootstrapped module, simply use the same name as used in .use().

Defines log file rotation type.

The valid types are:

  • year

  • month

  • day

  • hour

Default is day,

If true, the logging time will be in Unix timestamp.

Default is false.

Defines the buffer size for log data in bytes.

Default is 8128 bytes (8KB).

NOTE: File logging only.

Defines auto-buffer-flush interval in milliseconds.

Default is 5000ms (5 seconds).

NOTE: File logging only.

If true, file logging will be combined in to one file for all log levels.

Default is false.

NOTE: File logging only.

Defines the path to the logging directory.

If this is not set, gracenode will NOT log to file, but stdout/stderr stream only.

Default is not set.

If true, all logging will be outputting to stdout/stderr stream.

Default is true.

Defines the configurations to send logging data to a remote server via UDP protocol.

{
host: [string],
port: [int]
}

Default is not set.

If true, logging data will be colored.

Default is false.

If true, logging objects will show hidden properties.

Default is false.

Defines how far logging module should recursively output objects.

Default is not set.

Defines from which log level to output.

The valid log levels are:

  • verbose

  • debug

  • table

  • trace

  • info

  • warn

  • error

  • fatal

Use >, >= to control the definition of log level.

Example

'>= info'

The above example will be logging from log level info to lower (info, warn, error, fatal).

NOTE: From the top highest to lowest

Defines how many cluster worker processes.

If 0 is given, gracenode will not be running in cluster.

Default is 0.

If true, terminated worker processes will be automatically respawned and replaced.

Default is false.

If true, all workers will share a list of existing workers and their pid.

This may lead to server stress.

Default is true.

Tells gracenode to bootstrap and set up a given module.

gracenode will be loading the module from modulePath.

Assigns an optional functions to be executed for the bootstrapped module.

Structure:

{
config: [function],
setup: [function],
exit: [function]
}

A function to be executed when starting the gracenode process to read configuration data.

The assigned function be will passed a configuration data.

Example

gracenode.use('myMod', '/path/to/my/mod/', {
configfunction (configData) {
this.configData = configData;
}
});

NOTE: this in the function is the bootstrapped module.

A function to be executed when starting the gracenode process after options.config() if provided.

If options.config() is not provided, it will be called at the start of bootstrapping the module.

The function will be passed a callback function.

Example

gracenode.use('myMod', {
setupfunction (callback) {
// do something here 
callback();
}
});

NOTE: this in the function is the bootstrapped module.

A function to be executed on exitting of the gracenode process.

It is useful to clean up before the exit.

The function will be passed a callback function.

Example

gracenode.use('myMod', '/path/to/my/mod/', {
exitfunction (callback) {
// do something here 
callback();
}
});

NOTE: this in the function is the bootstrapped module.

Starts the gracenode process.

NOTE: If there is an error while starting the process, it will crush with an exception.

Stops the running gracenode process.

If an error object is passed, it will stop the process with an error.

Returns true if the process is running in cluster and the process is a master process.

Returns true if the process is running in cluster.

gracenode comes will built-in logging module.

It is accessed as gracenode.log.

In order to log some data, you need to create a logger.

var logger = gracenode.log.create();
logger.verbose('I am logging something here');
logger.info({ example: 'Example Object' });
var loggerWithName = gracenode.log.create('my logger');
loggerWithName.warn('warning!');

Defines a prefix to each logging data.

Returns an instance of logger object.

Log level verbose.

Log level debug.

Log level debug.

Log level debug.

Log level info.

Log level warn.

Log level error.

Log level fatal.

gracenode logger emits an even on each log output.

It is useful for capturing and sending all logging to a database etc.

gracenode.log.on('output', function (ip, logName, level, messageObj) {
// do something
});

There are some command-line options available for daemon.

node app.js --help, node app.js -h, ./gracenode --help, or ./gracenode -h.

Start an application as daemon.

./gracenode start app.js

node app.js start

Stop a running application.

./gracenode stop app.js

node app.js stop

Restart a running application.

./gracenode restart app.js

node app.js restart

Gracefully restart a running application.

This command works ONLY if your are running the application in cluster mode.

./gracenode reload app.js

node app.js reload

Stop all running daemon applications.

./gracenode stopall

node app.js stopall

To ignore prompting, add an option -f.

./gracenode stopall -f

node app.js stopall -f

Restart all running applications.

./gracenode restartall

node app.js restartall

To ignore prompting, add an option -f.

./gracenode restartall -f

node app.js restartall -f

Output running status of a daemon.

./gracenode status app.js

node app.js status

Output all running status of daemons

./gracenode list

node app.js list

Tails daemon log files.

./gracenode tail app.js

node app.js tail

Write log data into a file.

Daemonize the target application with the given interpreter.

Automatically restart the daemon process if watch file(s) change.

Be more verbose.

Stops or restarts all running daemon processes without user inputs. This option is for {stopall|restartall} command only.

Render allows you to create dynamic content from templated static files.

It also supports caching rendered data for static templates to improve the run-time performance.

It is useful for web pages etc.

A path to the pre-rendered file data to render.

An object to be inserted into the rendered file data.

An option to use cache for rendered template data.

If this parameter is not given, it does not use cache

The cache data will be ignored if given data is different from the cached rendered data.

NOTE: cacheTtl is in miliseconds. If the cache needs to last for 24 hours, cacheTtl = 8640000.

Default: Default cache TTL is 1 hour. Pass 0 to ignore caching.

Render requires a path to read the template files from.

It will then read all template files and pre-render them on the application process start.

render: {
path: '/path/to/my/templates',
*cacheSize: <number>
}

cacheSize is an optional configuration to change the default cache size in bytes.

Default cache size is 2MB.

Example:

var gn = require('gracenode');
gn.config({
render: {
path: '/path/to/my/template/files/'
}
});

Render can insert dynamically define values to rendered template file data.

gracenode allows access to the dynamically defined variables from the client-side javascript.

Example

To access the variable named example:

<script type="text/javascript">
 
console.log(window.gracenode.example);
 
</script>

All dynamically defined variables for rendered data can be accessed under window.gracenode.

Syntax

{{variableName}}

Example:

<div>{{myCar}}</div>
var rendered = gracenode.render('/myview.html', {
myCar: 'BMW'
});

The above examples will result in {{myCar}} being replaced by { myCar: 'BMW' }, so the rendered result is:

<div>BMW</div>

Render allows user custom functions to be registered and used in render templates.

Example:

gracenode.render.func('myFunction', function (variableValue) {
// do somethig here 
return variableValue * 2; 
});
var data = {
myValue: 4
};
var rendered = gracenode.render('/path/to/my/template', data);
This is my template. {{ myValue }} x 2 = {{ myFunction(myValue) }}.
This is my template. 4 x 2 = 8.

Render allows you define literals so that render does not attempt to render certain section of your templates.

Example:

{{literal if (A === B): Example endif literal}}

The above example will not render as if statement but rendered literally instead.

Render can combine multiple pre-rendered template files into one file and render it as one render data.

Syntax

{{require(/path/to/my/partial.html)}}

Render handles simple if statements.

WARNING: You must not have nested if statements.

WARNING: You must not have if statement inside of for statement.

Syntax

{{if ({a} === {b}):
<div>{a}&nbps;is&nbsp;{b}</div>
endif}}

Example:

{{if ({a} === {b}):
<div>{a}&nbps;is&nbsp;{b}</div>
else if (a > b):
<div>{a}&nbsp;is&nbsp;greater&nbps;than&nbsp;{b}</div>
else:
<div>{a}&nbps;is&nbsp;NOT&nbsp;{b}</div>
endif}}
var rendered = gracenode.render('myview.html', {
a: 100,
b: 10
});

IMPORTANT: The variables inside if must be {variableName} NOT {{variableName}}.

The above example will result in <div>{a}&nbsp;is&nbsp;greater&nbps;than&nbsp;{b}</div> to be in the rendered result:

<div>100&nbsp;is&nbsp;greater&nbps;than&nbsp;10</div>

Render handles simple for statements.

WARNING: You must not have nested for statements.

WARNING: You must not have if statement inside for statement.

Syntax

{{for (i = i < {list.length}; i++):
<div>{i}:{list.i}</div>
endfor}}

NOTE: {list.i} = list[i]

Example:

{{for (i = 0; i < {list.length}; i++):
<div>{i}:{list.i}</div>
endfor}}
var rendered = gracenode.render('/myview.html', {
list: [
'Apple',
'Carrot',
'Orange'
]
});

IMPORTANT: The variables inside for must be {variableName} NOT {{variableName}}.

The above example will result in:

<div>0:Apple</div>
<div>1:Carrot</div>
<div>2:Orange</div>

Render handles a simple for loop for object as foreach.

Syntax

{{foreach (key in {map}):
<div>{key}:{map.key}</div>
endforeach}}

NOTE:

{map.key} = map[key]

Example

{{foreach (key in {map}):
<div>{key}:{map.key}</div>
endforeach}}
var rendered = gracenode.render('/myview.html', {
map: {
meat: beef,
meat: pork,
fruit: apple,
veggi: beans
}
});

IMPORTANT: The variables inside foreach must be {variableName} NOT {{variableName}}.

The above example will result in:

<div>meat:beef</div>
<div>meat:pork</div>
<div>fruit:apple</div>
<div>veggi:beans</div>

Router lets you build HTTP server and REST endpoints easily.

gracenode.router

gracenode.router needs a port number and a host name to start the HTTP server.

router: {
port: <number>,
host: <string>
}

Example:

var gn = require('gracenode');
 
gn.config({
router: {
port: 8888,
host: 'localhost'
}
});
 
gn.start(function () {
// HTTP server is ready 
});
 

NOTE: Once you give port and host, gracenode will automatically start the HTTP server while gracenode.start().

You must register endpoint routes in order to setup your REST server with gracenode.router.

gracenode.router.get('/example', function (reqres) {
// respond as JSON 
res.json({ say: 'hello' });
});

gracenode.router allows you to define parameters in the request URLs.

Example:

The example below defines a URL parameter name.

GET /example/{name}
GET /example/Kevin

The above request URL will be routed to the handler of GET /example/{name}.

To access {name}:

exports.exampleHandler = function (req, res) {
// Kevin
var name = req.params.name;
};

granode.router allows you to define typed parameters.

Valid Types:

  • string

  • number

  • bool

  • object

Syntax

{type:paramName}

Example:

gracenode.router.get('/example/{number:id}/{string:name}');

POST, PUT, DELETE, PATCH, and HEAD

To register endpoints for request method other than GET, use the following:

gracenode.router.post(url [string], handler [function]);
 
gracenode.router.put(url [string], handler [function]);
 
gracenode.router.delete(url [string], handler [function]);
 
gracenode.router.patch(url [string], handler [function]);
 
gracenode.router.head(url [string], handler [function]);

GET and HEAD requests will not read request body by default.

In order to read request body of GET or/and HEAD add the following option:

gracenode.router.get('/read/req/body', getReqHandler, { readBody: true });

The handler functions of endpoints will be passed two arguments.

The first argument is req. It is an expanded request object.

Properties:

Request URL.

Request headers.

req.id

Unique ID for each request.

Object to hold user data for sharing the data among request hooks and handler.

Example:

// set session ID
req.args.sessionId = 'xxxx';
 
// you can use the session ID elsewhere
var sessionId = req.args.sessionId;

Object that holds GET query data.

Example:

// request URL: GET /example?id=1234
var id = req.query.id;

Object that holds URL parameters.

Example:

Example Request: GET /example/animal/info/cat.

gracenode.router.get('/example/{category}/info/{name}', function (reqres) {
// animal 
var category = req.params.category;
// cat 
var name = req.params.name;
// do somethinf 
});

Object that holds request body (For POST, PUT, DELETE, and PATCH).

Returns a cookie object.

Example:

How to set a cookie data

gracenode.router.login('/login', function (reqres) {
// do some loging operations here 
var cookies = req.cookies();
cookies.set('sessionId', sessionId);
// respond here 
});

How to get a cookie data

gracenode.router.get('/example', function (reqres) {
var cookies = req.cookies();
var sessionId = cookies.get('session');
});

Response object tat wraps the HTTP response object of node.js.

Object that holds response headers.

To Set Response Headers:

gracenode.router.post('/example', function (reqres) {
// set a custom header 
res.headers.sessionId = 'xxxx';
// respond 
res.html(htmlData);
});

Enable/Disable gzip compression of response data.

Default is true.

Executes a given callback function on unexpected connection close such as client timeout etc

Send response as JSON.

The default status is 200.

Send response as HTML.

The default status is 200.

Send response as plain text.

The default status is 200

File download response.

The default status is 200.

Stream file.

Useful for HTML5 video streaming etc.

Server a static file.

Send response as error (response data is JSON object).

The default status is 400.

gracenode.router allows you to setup request hook functions for your endpoints.

Useful for session varification etc.

Registered hook functions are executed on every match request.

Example:

gracenode.router.hook('/', hookForAllRequest);
gracenode.router.hook('/exmaple', hookForExampleRequest);
gracenode.router.hook('/example/one', hookForExampleOneReuqest);
 
gracenode.router.get('/example', exampleHandler);
gracenode.router.get('/example/one', exampleOneHandler);
  • GET /example will have hookForAllRequest, hookForExampleRequest as request hooks and they will be executed BEFORE exmapleHandler.

  • GET /example/one will have hookForAllRequest, hookForExampleRequest, and hookForExampleOneRequest as request hooks and they will be executed BEFORE exampleOneHandler.

Hook Function:

function hook(reqresnext) {
// call next() to move on to next hook or handler 
next();
}

Each hook function will have req, res, and next as arguments.

req is the expanded request object.

res is the response object.

next is the function to move on to next hook or handler.

NOTE: You may pass an error to next() to response as an error. The default status code is 400.

To change the status code, pass error.code = <status code> such as 500.

gracenode.router can optionally execute an error handler for specific error status such as 404.

This is useful when you need to display uniform 404 page on every 404 response etc.

Example:

gracenode.router.error(404, function (reqres) {
res.json({ message: 'Not Found'}, 404);
});

gracenode router can serve static files such as images etc.

Example:

var staticFileDirectoryList = [
'/public/',
];
gracenode.router.static('/static', staticFileDirectoryList);

The above example will create routes as:

NOTE: /public/ directory is treated as the document root directory and IS NOT present in routed URL.

GET /static/{file path}
GET /static/css/{file path}
GET /static/js/moredir/{file path}
// All subdirectories under /public will be routed

Example:

var staticFileDirectoryList = [
'/public/',
'/asset/'
];
gracenode.router.static('/static', staticFileDirectoryList);

The above example will create routes as:

NOTE: /public/ directory is NOT treated as the document root directory and IS present in routed URL.

When passing more than 1 static file directory paths, gracenode router will be routing static files as shown below:

GET /static/public/{file path}
GET /static/public/css/{file path}
GET /static/public/js/moredir/{file path}
GET /static/public/asset/{file path}
GET /static/public/asset/img/{file path}
GET /static/public/asset/video/{file path}
// All subdirectories under /public will be routed

NOTE: When service static files from your application, you must consider the file I/O load.

Each request will instruct the server to read from a file.


Returns a padded/none-padded with leading zero string.

Example:

var paddedNine = gracenode.lib.padNumber(9, 2);
// paddedNine = '09'; 
var nonePaddedTen = gracenode.lib.padNumber(10, 2);
// nonePaddedTen = '10'; 
var paddedTen = gracenode.lib.padNumber(10, 3);
// paddedTen = '010'; 
var nonePaddedHundred = gracenode.lib.padNumber(100, 3);
// nonePaddedHundred = '100'; 

Returns an array of date objects between startDate amd endDate.

Example:

var dates = gracenode.lib.getDates(new Date('2015-04-22'), new Date('2015-05-22'));
// dates will contain date objects between 2015/04/22 and 2015/05/22 

Returns an array of matched elements and their indexes/keys from either an object or an array.

If there are no matched elements, an empty array is returned.

Example With Array:

var list = [
        { name: 'Bob', age: 40 },
        { name: 'John', age: 37 },
        { name: 'Chris', age: 44 },
        { name: 'Dale', age: 51 }
];
var finder = function (elm) {
        return elm.age >= 40 && elm.age <= 50;
};
var matched = gracenode.lib.find(list, finder);
/*
matched: [
        { index: 0, element: { name: 'Bob', age: 40 } },
        { index: 2, element: { name: 'Chris', age: 44 } }
]
*/

Example With Object:

var map = {
        a00: { name: 'Bob', age: 40 },
        a01: { name: 'John', age: 37 },
        a02: { name: 'Chris', age: 44 },
        a03: { name: 'Dale', age: 51 }
};
var finder = function (elm) {
        return elm.age >= 40 && elm.age <= 50;
};
var matched = gracenode.lib.find(map, finder);
/*
matched: [
        { index: 'a00', element: { name: 'Bob', age: 40 } },
        { index: 'a02', element: { name: 'Chris', age: 44 } }
]
*/

Converts a given string value to appropriate data type.

Example:

var num = gracenode.lib.typeCast('100');
// 100
var float = gracenode.lib.typeCast('1.5');
// 1.5
var truthy = gracenode.lib.typeCast('true');
// true
var obj = gracenode.lib.typeCast('{"example":1,"blah":"test"}');
// { example: 1, blah: 'test' }

Returns a pseudo-random integer between min and max.

Returns a pseudo-random floating point number between min and max.

The thrid argument "precision" is optional and default is 2.

Returns an array of arguments that the given function expects.

 
function foo(num1num2) {
        return num1 + num2;
}
 
var args = gracenode.lib.getArguments(foo);
// args = ["num1", "num2"]; 

Recursively walks the given path and passes an array of file paths to the callback function.

Returns a clone of given object. In javascript, objects are passed around as references. Use this in order to avoid mutating the original objects.

If propNames is given, the function will clone ONLY the properties given in propNames array.

Returns an instance of TimedData that changes its value over time.

Configs:

{
    "max": 10, // maximum value 
    "min": 0, // minimum value 
    "interval": 60000, // value increments/decrements every "interval" 
    "step": 1, // at every interval, the value increments/decrements by "step" 
    "type": "inc", // either "inc" for incrementing type of "dec" for decrementing type 
    init: 10 // initial value to start with 
}

Usage Example:

TimedData that recovers its value by 1 every 1 second.

var config = {
max: 10,
min: 0,
interval: 1000,
step: 1,
type: 'inc',
init: 0
};
var td = gracenode.lib.createTimedData(config);
setTimeout(function () {
var value = td.getValue();
// value should be 1 
}, 1000);
var config = {
max: 10,
min: 0,
interval: 1000,
step: 1,
type: 'inc',
init: 10
};
var td = gracenode.lib.createTimedData(config);
td.dec(5);
setTimeout(function () {
var value = td.getValue();
// value should be 6 
}, 1000);

Returns the current value.

Increments the current value by incrementValue.

Returns true if successful.

Decrements the current value by decrementValue.

Returns true if successful.

Resets the state of TimedData object to its initial state.

Returns maximum value.

Returns minimum value.

Returns the interval for every update in milliseconds.

Returns the value of step for every update.

Returns a JSON format of TimedData object.

Returns an instance of DateTime object.

time can be a YYYY-MM-DD HH:MM:SS style string, javascript Date object, or timestamp such as Date.now().

Example:

var dt = gracenode.lib.createDateTime();
var fomratted = dt.format('m/d/Y H:M:S');
// e.g. 04/28/2015 21:13:09 

Returns a formatted date time string.

If default format is set and the format string is not passed to .format(), default format will be used.

Example With Format:

var dt = gracenode.lib.createDateTime('2015-04-30 09:52:00');
var formattedDate = dt.format('m/d/y H:M');
console.log(formattedDate);
// 04/30/15 09:52 

Example With Default Format:

var dt = gracenode.lib.createDateTime('2015-04-30 14:30:00', 'Y/m/d H:I');
var formattedDate = dt.format();
console.log(formattedDate);
// 2015/04/30 02:30 
Format Meaning
y The last 2 digit of the year
Y Year
m Month with leading 0
n Shortened name of a month
f Full name of a month
d Date with leading 0
H Hours with leading 0 in 24 hours format
I Hours with leading 0 in 12 hours format
M Minutes with leading 0
S Seconds with leading 0
N Milliseconds with leading 0

Offests the date.

NOTE: By giving more than 30 days or 365 days, it can exceed current year or month.

Example:

var dt = gracenode.lib.createDateTime();
// 1 day in the future
dt.offsetInDays(1);
var dt = gracenode.lib.createDateTime();
// 1 day in the past
dt.offsetInDays(-1);

Offests the hours.

NOTE: By giving more than 24 hours, it can exceed current date and so on.

Example:

var dt = gracenode.lib.createDateTime();
// 1 hour in the future
dt.offsetInHours(1);
var dt = gracenode.lib.createDateTime();
// 1 hour in the past
dt.offsetInHours(-1);

Returns a unix timestamp in milliseconds.

Returns an array of DateTime objects within the given range.

NOTE: date can be either DateTime or Date.

Example:

var dt = gracenode.lib.createDateTime('2015-01-01');
var dates = dt.getDaysInRange(gracenode.lib.createDateTime('2015-01-10'));
// dates = [ ... ]; 
// dates will contain instances of DateTime object from 2015-01-01 to 2015-01-10