node.js fragments - part 1

This are gonna be some fragments of common code of node.js, some were used for nomination, hopefully you will find them useful and comeback for reference

Version en espaƱol

The always needed first program

Loading modules

First part on the file is loading a module, the modules are loaded with require, to understand more about require check this post, plus read the documentation about it

Besides just loading them, you can pass them parameters like

require('./routes/index')(app, log);

In this case we are passing some vars to the require module


Also in the first program, we can see the console.log to print out information in the console, this is useful at debugging time or to show information to the user, check the documentation for more information about using the console, there are also different levels to show the information besides there are a lot of modules that extend the functionality, some print out in colors, prettify the information, etc.

Create a server

Besides creating a serve with the http module and tell the port and the ip to listen, we can create servers with other modules, one of the most common is express, to create it with express its simple:

var app = module.exports = express.createServer();

And then we can tell it in which port to listen


You can pass the ip also, by default it takes the '' which means everywhere

There are a lot of other modules to create servers, do a quick search in github or npm to find the one that suit you better, most of them follows the same pattern

Read and write files

For this we have a nice module called "fs" or filesystem, this module have everything needed for read, write, etc in files, links or directories

FS have the option to do the operations in async or sync way, as a good practice try to always do it async


fs.readFile('data.txt', function (err, data) {
  if (err)
    throw err;
  if (data)

fs.readdir('.', function (err, files) {
 if (err)
    throw err;
 for (var index in files) {


fs.writeFile('data.txt', 'Hello, World!', function (err) {
     if (err)
       throw err;

Check attributes

fs.stat('data.txt', function (err, stats) {
  if (err)
     throw err;
  if (stats.isFile()) {
      console.log('It\'s a file!');
  if (stats.isDirectory()) {
    console.log('It\'s a directory!');

For more information check the documentation

Also you can use async.js to do it even more easy the async manipulation of files


In case you want to log information to a file for future references, you can use some modules for this, in the case of nomination we use "log.js" which is quite simple to use:

Log = require('log'),
log = new Log(),
fs = require('fs');

First we have to load the module and create an object which is the one that we are going to use in the app to log information, then we have to load fs, because we need to create the file were we are going to write

log.level = Log.DEBUG;
log.stream = fs.createWriteStream('logs/dev.log', { flags: 'w' });
log.notice('logging today:' + new Date());

After we tell the level of logs the file will have, this should be changed depending on the configuration that we are going to use, we may want to have less level of log traces for production for example

After create the file lets add it to the stream and we just need to start logging information with different levels

Check the documentation for log.js, and also there are alot of modules to do logging, from manual stuff like the one we use here to others that are helpers or middleware for some frameworks like express/connect, etc, check more modules


Since we use alot of async in our node.js programs we end up using a lot of callbacks, callbacks are nothing more than where our function will return after doing its process, the convention for calling the callback its always return an error even if there isn't any and then the data


function hello (user, callback) {
    if (!user){
        callback(new Error('no user :('));
    var msg = 'hello' + user;
    callback(null, msg);

And from where we call it

hello('newuser', function (error, msg) {
    if (error) { console.log(error.msg); return; }

In this case you always check if there happened any error or not and its more easy to control the flow


We recommend to use the "new Error()" to send your errors instead of only one string, because new Error have information about the error, where did it happened, etc, this information its very important to debug the problems and have a better idea of what its going on in the code, with the string only we could lose some of that information, check the callback information above for more information about sending errors.

Also you can see more information about this in this post

Also is recommended to use an error listener, to catch even more errors that we may be missing as described here

var events = require('events')
emitter = new events.EventEmitter()

function y(arg, callback) {
    if (arg === 1) {
    } else {
 function onTick() {
     try {
     } catch(err) {
  emitter.emit('myerror', err)


Well nice first fragments, i will continue to update with more posts about this in node.js

If you are looking for some special information please ask for it in the comments i will try to post something about it


No comments:

Post a Comment