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

1 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);
    // { A: 2, B: 14, C: 6 }
});

From JR's : articles
211 words - 1700 chars - 1 min read
created on
updated on - #
source - versions



A     A     A     A     A

© 2013-2017 JotHut - Online notebook

current date: Dec 23, 2024 - 8:39 p.m. EST