Installing
Installing in Ubuntu
Installing Node via Package Manager
sudo apt-get install nodejs
sudo apt-get install npm
Install Locations
npm - /usr/share/npm
First Steps
Creating an Empty Project
npm init
npm init create an empty node project, which is a package.json file. The file will look something like this…
{
"name": "projectName",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Adding Test Framework for specific location
We use mocha with chai.
- Mocha is a test framework for JavaScript.
- Chai is a BDD / TDD assertion library for node
By default the package.json file does not have any test framework setup. To leverage mocha, adjust the “test” attribute to look as follows…
...
"scripts": {
"test": "mocha sourceDir testDir --watch"
},
...
sourceDir & testDir are directories where your source and test code are located. Using the –watch means that mocha will rerun everytime there is a source code change.
To start your test framework enter the following…
npm test
Adding Test Framework for file convention
The following runs all tests under the src folder that match the file extension .test.js
"scripts": {
"test": "find ./src -iregex '.*.test.js' | xargs mocha -u tdd --reporter spec"
},
Working with Dates
The Moment.js library a good library for handling dates in js.
General
Also called NTier Pattern
Node References
Modules
Old approach
In you module file doSomethingModule.js…
module.exports = {
doSomething: function() {
return "something";
}
}
in the file you want to consume it from…
var obj = require("../doSomethingModule.js");
console.log(obj.doSomething()); // return something
New approach
In you module file doSomethingModule.js…
module.exports = class TheClass{
doSomething() {
return -1;
}
}
in the file you want to consume it from…
var objType = require("../doSomethingModule.js");
var theObject = new objType();
theObject.doSomething(); // return something
Module Patterns
Express
Hosting
Running Node as a background service
Latest Running Node as a background service
Sessions
app.js
app.use(express.cookieParser());
app.use(express.session({secret: '1234567890QWERTY'}));
in your routing…
var session = require('express-session');
app.get('/awesome', function(req, res) {
req.session.lastPage = '/awesome';
res.send('Your Awesome.');
});
Express References
Express 4.x API
Express source code
Express tutorials
express.static
Morgan
Soup to Bits: Building Blocks of Express.JS
Soup to Bits: Real-time Web With Node.JS
CodeSchool Discussion Forum