William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

Tag Archives: Node.js

NodeJS: the good parts?

NodeJS: the good parts? A Skeptic’s View

Here is a interesting video in youtube: NodeJS: the good parts? A Skeptic’s View, which I extract and did a simple summary.
The node-promise is very interesting which I probably use in future.

------@@ Node.js ------
Long running computations => blocks event loop for other requests
Need to run outside of main event loop
Options:
community: web workers threads
Built-in: NodeJS child processes

Micro-service rchitecture

1. Modules
---------
foo.js: exports.sayHello = function() {}
var foo = require("foo");
foo.sayHello();

2. Node as static files service:
--------------------------------
fs.exists(filePath, function(exists) {
  if(exists) {
    res.writeHead(200, {"content-type": mime.lookup(path.basename(filePath)) });
	fs.createReadStream(filePath).pipe(res);
  }
 });
 or:
 app.configure(function() {
   app.use(express.static(__dirname + '/public'));
 });

3. RESTful WS with express/restify:(Easy URL routing and destructuring)
-----------------------------------
app.get('/portfolio/:userId', function(req, res) {
  var portfolio = retrievePortfolio(req.params.userId);
  res.json(portfolio);
});

-- Use 'request' module to pass: Proxying to backend Servers

4. Deliverying events to the browser
-------------------------------------
websocket, socket.io

5. Promises (simply codes)
---------------------------
https://github.com/kriszyp/node-promise

Most used Node.js modules

Most used Node.js modules

Here I list some most used Node.js modules, some from npmjs.org, some from my collection, some from my projects

underscore
async
request
optimist - Light-weight option parsing with an argv hash.
jshint
node-inspector
supervisor

connect
socket.io
segment.io
jslint
jsFiddle

restify
Passport - Simple, unobtrusive authentication for Node.js.

compound.js
express.js
Geddy | The original MVC Web framework for Node
TodoMVC
Meteor
Tower
Mocha
grunt - The JavaScript Task Runner

Kendo UI - jQuery HTML5 framework for desktop, mobile app development, HTML5 data visualization
Initializr - Start an HTML5 Boilerplate project in 15 seconds!
HTML5 Boilerplate
Minify

Selenium - Web Browser Automation
Create.js is a comprehensive web editing interface for Content Management Systems.

mongoose
redis

working tips: jshint, async.js

working tips: jshint, async.js

//@@
jshint
async.js
node-inspector

//@@ json and javascript object converts
JSON.stringify and JSON.parse are almost oposites:
var obj = {...};
var json = JSON.stringify(obj);
var obj2 = JSON.parse(json);
so that obj and obj2 are "the same".

//@@ webstorm sync linux git repository.
rsync
192.168.20.225 server
jdk
c:cygwin64
c:ant
set env path
sshkey-gen
in webstorm/ldrly project: ant to use build.xml (properties)

//@@
git checkout commit_tag
git rm somefile --cached && git commit && git push

//@@ JetBrains' Webstorm
ctrl+shift+a
CTRL + SHIFT + F
CTRL + R
CTRL + ALT + I

Node.js REST APIs example

Node.js REST APIs example

The following is a very basic and standard REST API example, with the require(‘mongoose’) in expressjs.

var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

// required: true,
var Task = new Schema({
  task : String,
  created_at: { type: Date, default: Date.now },
  updated_at : Date
});

var Task = mongoose.model('Task', Task);
...

app.get('/api/tasks', function(req, res, next){
  Task.find({}, function (err, docs) {
    res.json(docs);
  });
});

app.post('/api/tasks', function(req, res){
  var doc = new Task(req.body.task);
  doc.save(function (err) {
    if (!err) {
      res.json(doc);
    } else {
      res.send(err, 422);
    }
  });
});

app.get('/api/tasks/:id', function(req, res){
  Task.findById(req.params.id, function (err, doc){
    if (doc) {
      res.json(doc);
    } else {
      res.json(404);
    }
  });
});

app.put('/api/tasks/:id', function(req, res){
  Task.findById(req.params.id, function (err, doc){
    if (!doc) {
      res.json(404)
    } else {
      doc.updated_at = new Date();
      doc.task = req.body.task.task;
      doc.save(function (err) {
        if (!err) {
          res.json(doc);
        } else {
          res.send(err, 422);
        }
      });
    }
  });
});

app.del('/api/tasks/:id', function(req, res){
  Task.findById(req.params.id, function (err, doc){
    if (doc) {
      doc.remove(function() {
        res.json(200)
      });
    } else {
      res.json(404)
    }
  });
});

The calling is like: