node package manager

Introducing npm Enterprise add-ons. Integrate third-party dev tools into npm…

gracenode

A node.js framework for real-time applications over UDP and TCP protocols with extendable modules for quick and clean evelopment.

gracenode 3

©Nobuyori Takahashi < voltrue2@yahoo.com >

A node.js framework for real-time applications.

Version 0.12.10 or above.

  • Manages cluster process. Read here.

  • 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 UDP server for real-time application. Read here.

  • Provides RPC server over TCP for real-time application. Read here.

  • Provides built-in session management as an option. 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.http.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
    },
    http: {
        // you must have this value if you need to use gracenode.http 
        port: 8888,
        // you must have this value if you need to use gracenode.http 
        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 terminate 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', {
    setup: function (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.http.get('/', function (req, res) {
    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({
    http: {
        port: <number>,
        host: <string>
    }
});

Registers a routing for GET requests.

Example:

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

More Details Here

gracenode comes with built-in session management for HTTP, UDP, and RPC server.

For more details read here.

For real-time applications, garcenode comes with UDP server.

For more details read here.

gracenode comes with RPC real-time application solution over TCP.

For more details read here.

gracenode manages cluster and communications between cluster nodes.

gracenode uses cluster-mode module to manage clustering and process to process communication.

More details is 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/', {
    config: function (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', {
    setup: function (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/', {
    exit: function (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 crash 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.


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(num1, num2) {
        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 deep copied object. Use this function instead of gracenode.lib.cloneObj().

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 

Returns a UUID object.

Example:

var uuid = gracenode.lib.uuid.v4();
// 128 bits UUID string 
var uuidString = uuid.toString();
// UUID in raw binary 
var uuidBuffer = uuid.toBytes();
// length of UUID string 
var uuidStringLen = uuid.getLength();
// length of UUID binary 
var uuidBuffLen = uuid.getByteLength();

Creates a UUID object from input.

input can be a UUID string, UUID binary, or UUID object.

Creates a binary packet of fixed format for a command request used in UDP and RPC.

Creates a binary packet of fixed format for a reply (to a command request) used in UDP and RPC.

Creates a binary packet of fixed format for a push message from server used in UDP and RPC.

Parses a binary packet used in UDP and RPC to an object.