Node.js is a versatile framework, implementing the CommonJS standard library within the code. This allows you to extend the framework to perform tasks that were not originally conceived of within Javascript. Such modules allow for system calls, filesystem calls, and I/O. However, you can use the same syntax to create your own modules to integrate in your Node server.
Simple Concatenation Module
In order to begin, create a Javascript file in your working node directory, with the naming convention [merge.js]. For the first example, we will write a module that has a function that concatenates two strings, with a space, and returns the new value.
In your [merge.js] file, you will want to input the code:
return stringOne + " " + stringTwo;
};
Here you can see that we use the exports object to create the method concatenate. This method has the function of concatenating stringOne and stringTwo, with a space in between. Now that we have a module, we need to include it in the main JS file. In your main server file, or wherever you need to include the module, add the following code to the top:
Later in your code, you can then call the method by writing:
console.log(string);
Logging Module
For a secondary exampole, I will use a modified version of my node logging function. Feel free to create an empty Javascript file, and name it [nlog.js]. Here, you will want to input the code:
var fs = require("fs");
var path = "access_log";
var now = new Date();
var dateAndTime = now.toUTCString();
stream = fs.createWriteStream(path, {
'flags': 'a+',
'encoding': 'utf8',
'mode': 0644
});
stream.write(dateAndTime + " ", 'utf8');
stream.write(request.connection.remoteAddress + ": ", 'utf8')
stream.write(request.method + " ", 'utf8')
stream.write(request.url + "\n", 'utf8');
stream.end();
return true;
}
From your main server JS file, you will want to import the module using require, as follows:
In order to actually use the logging method, your main code will need to call the method:
Now that you know the basics, you should be well equipped to begin writing your own Node modules.
Tags: javascript, log, modules, node.js