You're viewing old version number 6. - Current version

2 min

Node.js code snippets

Learning Node.JS Programming

hello-console.js

// Call the console.log function.
console.log("Hello World.");

hello-server.js

// Load the http module to create an http server.
var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
    var server = http.createServer(function (request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.end("Hello World\n");
});

// Listen on port 8080, IP defaults to 127.0.0.1
server.listen(8080);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8080/");

Require Hello

hello.js

exports.world = function() {
    console.log('Hello World');
}

main.js

var hello = require('./hello');
hello.world();

execute:

$ node main.js

Parsing log file

my_parser.js

// Load the fs (filesystem) module.
var fs = require('fs');//

// Read the contents of the file into memory.
fs.readFile('example_log.txt', function (err, logData) {

    // If an error occurred, throwing it will
    // display the exception and kill our app.
    if (err) throw err;

    // logData is a Buffer, convert to string.
    var text = logData.toString();

    var results = {};

    // Break up the file into lines.
    var lines = text.split('\n');

    lines.forEach(function(line) {
        if ( line.length ) {
            var parts = line.split(' ');
            var letter = parts[1];
            var count = parseInt(parts[2]);

            if(!results[letter]) {
                results[letter] = 0;
            }

            results[letter] += parseInt(count);
        }
    });

    console.log(results);       
});

example_log.txt

2013-08-09T13:50:33.166Z A 2
2013-08-09T13:51:33.166Z B 1
2013-08-09T13:52:33.166Z C 6
2013-08-09T13:53:33.166Z B 8
2013-08-09T13:54:33.166Z B 5

execute:

$ node my_parser.js

output:

$ { A: 2, B: 14, C: 6 }

Parse Log File Object Oriented Version

parser.js

// Parser constructor.
    var Parser = function() {
};

// Parses the specified text.
Parser.prototype.parse = function(text) {

var results = {};

// Break up the file into lines.
var lines = text.split('\n');

lines.forEach(function(line) {
    if ( line.length ) {
        var parts = line.split(' ');
        var letter = parts[1];
        var count = parseInt(parts[2]);

        if(!results[letter]) {
            results[letter] = 0;
        }

        results[letter] += parseInt(count);
    }
});

return results;
};

// Export the Parser constructor from this module.
module.exports = Parser;

my_parser_oo.js

// Require my new parser.js file.
var Parser = require('./parser');

// Load the fs (filesystem) module.
var fs = require('fs');

// Read the contents of the file into memory.
fs.readFile('example_log.txt', function (err, logData) {
    // If an error occurred, throwing it will
    // display the exception and kill our app.
    if (err) throw err;

    // logData is a Buffer, convert to string.
    var text = logData.toString();

    // Create an instance of the Parser object.
    var parser = new Parser();

    // Call the parse function.
    console.log(parser.parse(text));        
});

execute:

$ node my_parser_oo.js

output:

$ { A: 2, B: 14, C: 6 }

counter.js

var http = require('http');

var userCount = 0;
http.createServer(function (request, response) {
    console.log('New connection');
    userCount++;

    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.write('Hello!\n');
    response.write('We have had '+userCount+' visits!\n');
    response.end();
}).listen(8081);

console.log('Server started');

counter.js will double the count each time the browser is refreshed because in addition to accessing the server, the browser also makes a request for the favicon, which increments the counter too.

Express - static-file-server.js

var express = require('express'),
app = express();
app.use(express.static(__dirname + '/public'));
app.listen(3000);

in document root, execute:

$ mkdir public
$ cd public
$ vim test.html

in browser:

http://site:3000/test.html

From JR's : articles
509 words - 4106 chars - 2 min read
created on
updated on - #
source - versions



A     A     A     A     A

© 2013-2017 JotHut - Online notebook

current date: Nov 15, 2024 - 5:44 p.m. EST