Recently I started using CodeSchool to explore new languages/technologies in the web world, and I will post every Tuesday something new that I learn. So far, all I have for them is pure praise, so if you fancy learning something new go check them out. I like them because of one thing in how they do their presentations: first you watch a video in which they explain the concept and then, more importantly (at least in my case), you get the set of challenges where you yourself have to write the code in order to pass on to the next level – awesome! So I would say that their slogan “Learn by doing” is right on the spot.
This is by no means meant as a tutorial, but merely as my notebook where I write down things which I’ve learned. Ok, without further to do, lets check out what’s all this mumbo jumbo buzzword about Node.js.
Node.js (by Ryan Dahl) is in fact a wrapper, written in C, around V8 JavaScript runtime of Google Chrome engine which can be executed on the server.
Blocking vs non-blocking code: Node.js makes non-blocking possible by providing us with a callback function when the process (for example: file reading) is done.
var http = require("http"); var fs = require("fs"); http.createServer(function(request, response){ response.writeHead(200); fs.readFile("file.txt", function(err, contents){ response.write(contents); response.end(); }); response.write("This will most likely be printed before the file contents"); }).listen(8080);
To view this, visit http://localhost:8080 in your browser or do a curl request. Interesting thing to note though is that you will not get the same effect if you run it via curl in terminal and in browser, and here is my question on StackOverflow which helps answer why. Long story short (with more info about it later in the post):
…this is simply due to the behavior of the browser rendering engine which cashes the contents until response.end(); arrives, and then renders whole response. Socket.IO and this article should be of help
As explained in the StackOverflow post, I solved this by using Socket.IO (explained in more detail below in the post) and here is the simple example:
//timeoutTest.js var express = require('express'), app = express(), server = require('http').createServer(app), io = require('socket.io').listen(server); server.listen(8080); app.use(express.static(__dirname + '/')); app.get('/', function (req, res) { res.sendfile(__dirname + '/timeoutTest.html'); }); io.sockets.on('connection', function (client) { client.emit('msg', "This prints right now on connection."); setTimeout(function(){ client.emit('msg', "This prints out after 3 secs."); }, 3000); }); //timeoutTest.html <!DOCTYPE html> <html> <head> <script src="/socket.io/socket.io.js"></script> <script src="jquery.js"></script> <script> $(document).ready(function(){ var server = io.connect('http://localhost'); server.on('msg', function(data){ $('body').append(data + "<br/>"); }); }); </script> </head> <body> </body> </html>
Upon first execution of the code Node registers events and then it goes into the so called “event loop”.
Instead of response.write(string) as the last command, you can put it in end() function like this response.end (string);
How to use event emmiters:
var EventEmitter = require('events').EventEmitter; var logger = new EventEmitter(); logger.on('error', function (msg){ console.log('error: ' + msg); }); logger.emit('error', 'sth went wrong');
Same “#$! different packaging:
http.createServer(function(req, resp){}); //is the same as: var server = http.createServer(); server.on("request", function(req, resp){};
Pip | ing:
var fs = require('fs'); var http = require('http'); http.createServer(function(request, response){ var newFile = fs.createWriteStream('newFile.md'); request.pipe(newFile); request.on('end', function(){ response.end('uploaded'); }); }).listen(8080); //test like this: curl --upload-file someFile.txt http://localhost:8080
File uploader:
var fs = require('fs'); var http = require('http'); http.createServer(function(request, response) { var newFile = fs.createWriteStream("readme_copy.md"); var fileBytes = request.headers['content-length']; var uploadedBytes = 0; request.pipe(newFile); request.on('data', function(chunk) { uploadedBytes += chunk.length; var progress = (uploadedBytes / fileBytes) * 100; response.write("progress: " + parseInt(progress, 10) + "%\n"); }); request.on('end', function(){ response.end('uploaded'); }); }).listen(8080);
A side-note; console.log() does in fact call process.stdout.write.
While calling your own modules, you require them without the “.js”
//custom_hello.js file var hello = function() { console.log("hello!"); } exports = hello; //custom_goodbye.js file exports.goodbye = function(){ console.log("whot!?"); } //--usage: var hello = require('./custom_hello'); var gb = require('./custom_goodbye'); hello(); gb.goodbye();
When you’re requiring with “./” it searches in the current file directory. When, however, you search without it and just write the name of the module it first searches in the file directory for a folder named node_modules, then it goes folder up if it doesn’t find it in recursive.
npm install request installs it locally and you can (only then!) require it in your code, whilst you should do a global installation npm install coffee-script -g if the module has an executable.
//package.json { "name": "My Awesome Node App", "version": "1", "dependencies": { "connect" : "2.2.1", "underscore" : "1.3.3" } }
package.json file is cool as you can distribute the “barebones” app, which once downloaded can be fully installed by doing npm install (it also installs sub-dependencies if needed).
Express – web application framework for Node.js: npm install express
var express = require('express'); var app = express(); //prior versions: express.createServer(); app.get('/:param', function(request, response){ var param = request.params.param; response.send(param); //or, templates are also supported! response.render('tweet.ejs', {tweets: tweets, name: username}); }); app.listen(8080); //tweet.ejs <h1>Tweets for <%= name %></h1> <ul> <% tweets.forEach(function(tweet)){ %> <li><%= tweet.text %></li> <% }; %> </ul> //but, also you need layout.ejs <!DOCTYPE html> <html> <head> <title>Some cool title</tile> </head> <body> <%- body %> </body> </html>
Socket.IO – aims to make realtime apps possible in every browser and mobile device.
npm install socket.io
Simple chat application
var express = require('express'), app = express(), server = require('http').createServer(app), io = require('socket.io').listen(server); server.listen(8080); app.use(express.static(__dirname + '/')); app.get('/', function (req, res) { res.sendfile(__dirname + '/chat.html'); }); io.sockets.on('connection', function (client) { client.on('join', function(name){ client.set("nickname", name); }); client.on("msg", function(data){ client.get("nickname", function(err, name){ client.broadcast.emit('msg', name + ":" + data); }); }); });
Very important thing to note here is that in order to make use of jQuery library you have to set the correct path to your js files in the app.use() function.
<!DOCTYPE html> <html> <head> <title></title> <script src="/socket.io/socket.io.js"></script> <script src="jquery.js"></script> <script> $(document).ready(function(){ var server = io.connect('http://localhost'); server.on("connect", function(data){ nickname = prompt("Your nickname:"); server.emit("join", nickname); }); server.on('msg', function(data){ $('#recv').append(data + "<br/>"); }); $("#send").on("click", function(event){ event.preventDefault(); $('#recv').append($('#msg').val() + "<br/>"); server.emit('msg', $('#msg').val()); }); }); </script> </head> <body> <input type="text" id="msg" name="msg" value="testets"/> <input type="submit" id="send" name="send"/> <div id="recv" name="recv"></div> </body> </html>
mongoDB – open-source document database, and the leading NoSQL database written in C++. mongojs – A Node.js module for mongodb, that emulates the official mongodb API as much as possible. Installation via npm: npm install mongojs .
//db.js var databaseURI = "mydb"; var collections = ["users"]; var db = require("mongojs").connect(databaseURI, collections); module.exports = db; //dbtest.js var db = require("./db"); db.users.save({email: "[email protected]", group: "A"}, function(err, saved) { if( err || !saved ) console.log("User not saved"); else console.log("User saved"); }); db.users.find({group: "A"}, function(err, users) { if( err || !users) console.log("No A group users found"); else users.forEach( function(user) { console.log(user); }); });
In order for this to work mongoDB has to be installed on your system and it has to be running. Installation instructions are clear and concise on their website, but a tl;dr is: download the zip package, unzip in c:\mongodb , make c:\data\db folder, run c:\mongodb\bin\mongod.exe.