./my_module.js
var msg = "x:"; //private
var f = function(x) {
return msg + " " + x;
}
module.exports.f = f; //public
Export module functions making them part of module.exports
var module = require('module'); //library module
var my_module = require('./my_module'); //local module
console.log(my_module.f("hello"));
Import modules with require
package.json
./package.json
{
"name": "my-app",
"description": "My Web Application",
"version": "0.0.1",
"dependencies": {
"express": "3.x"
}
}
dependencies
lists the required modules and their version
Use the Node Package Manager (npm
) to:
npm init
interactively create a new package.json
npm install
download and install the dependencies
var express = require('express');
var app = express();
app.get('/',
function(req, res) { db.findAll(function(error, model) {
res.render('view', model);
}) });
app.listen(8888);
app.METHOD('URI Template', callback)
METHOD = {get, put, post, delete, all}
app.get('/user/:id',
function(req, res){
res.send('user ' + req.params.id);
});
app.get('/file/*.*',
function(req, res){
res.send('file path: ' + req.params);
});
app.routes //read the configuration
app.use(express.bodyParser());
app.put('/blog/:year/:id?', //? optional
function(req, res){
var year = req.params.year;
var id = req.params.id || 0; //default 0
var body = req.body; ...
var files = req.files; //uploaded files
});
//Request Content-Type:application/json
if (req.is("application/json")) {
//req body is JSON
}
//Request Accept:text/html
if (req.accepts("html")) {
//set Response Content-Type Header
res.type("text/html");
}
function(model) { return html }
Views are template files that present content to the user: variables, arrays and objects that are used in views are passed by the controller to be rendered by the view.
Views should not contain complex business logic; only the elementary control structures necessary to perform particular operations, such as the iteration over collections, and simple filters.
function(model) {
var html = [];
html.push('<html><body>');
if (model.user) {
html.push('<h2>' + model.user.name + '</h2>');
}
html.push('</body></html>');
return html.join();
}
res.render('view template', { model } );
Invoke a template to render the view
//render the index template using JADE
res.render('index.jade');
//render the index template using EJS
res.render('index.ejs');
app.set('view engine', 'ejs');
res.render('index');
app.js
var model = {
user: { name: 'CP' }
};
res.render('index.ejs', model );
index.ejs
<html><body>
<% if (user) { %>
<h2><%=user.name %></h2>
<% } %>
</body></html>
Result
<html><body>
<h2>CP</h2>
</body></html>
.ejs
<h1><%= title %></h1>
<ul>
<% for(var i=0; i<list.length; i++) {%>
<li><%= link_to(list[i],
‘users/'+list[i]) %></li>
<% } %>
</ul>
<% %>
is executed<%= %>
adds the result to the HTMLReduce the amount of code by using these helper functions (mini-templates or widgets)
date_tag form_tag form_tag_end hidden_field_tag
input_field_tag is_current_page link_to
submit_link_to link_to_if link_to_unless
password_field_tag select_tag submit_tag
text_area_tag text_field_tag img_tag
http://code.google.com/p/embeddedjavascript/wiki/ViewHelpers
A collection is a set of JSON objects, which may or may not have the same structure
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/db');
// The MongoDB Server should be running
// for the connection to work
var CommentsSchema = new mongoose.Schema ({
person : String
, comment : String
, created_at : Date
});
var PostSchema = new mongoose.Schema({
id : mongoose.ObjectId
, author: String
, title : String
, body : String
, created_at : Date
, comments : [CommentsSchema]
});
//Create the Collection ‘Post’ using Schema
mongoose.model('Post', PostSchema);
var Post = mongoose.model('Post');
Post.find({},
function (err, posts) {
//for each post in posts
});
Post.findById(id,
function (err, post) {
if (!err) { //found post with id
}
});
Save also works with updates
var post = new Post(
{ title: params['title'],
body: params['body'],
created_at: new Date() });
post.save(function (err) { //save failed
});
Post.findById(id,
function (err, post) {
if (!err) {
post.remove();
}
});
Use a spacebar or arrow keys to navigate