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

5 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

Express - Hello World

var express = require('express');
var app = express();

app.get('/', function(req, res){
    res.send('hello world');
});

app.listen(3000);

Express - Hello World - Version 2

var express = require('express');
var app = express();

app.get('/', function (req, res) {
    res.send('Hello World!');
});

var server = app.listen(3000, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at http://%s:%s', host, port);
});

Express - Router

router.js

var express = require('express');
var app = express();

// respond with "Hello World!" on the homepage
app.get('/', function (req, res) {
    res.send('Hello World from router.js\n');
});

// curl http://127.0.0.1:3000/user?name=jr
app.get('/user', function (req, res) {
    var username = req.query.name;
    if ( username != undefined && username.length > 0 ) {
        res.send('user req for: ' + req.query.name + '\n');
    } else {
        res.send('user name missing\n');
    }
});

// accept POST request on the homepage
app.post('/', function (req, res) {
    res.send('Got a POST request. name=\n');
})

// accept PUT request at /user
app.put('/user', function (req, res) {
    res.send('Got a PUT request at /user\n');
})

// accept DELETE request at /user
app.delete('/user', function (req, res) {
    res.send('Got a DELETE request at /user\n');
})

// start server and listen on port 3000
var server = app.listen(3000, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at http://%s:%s', host, port);
});

execute:

$ curl http://127.0.0.1:3000/user?name=jr

Post URI

var express = require('express');
var app = express();

// respond with "Hello World!" on the homepage
app.get('/', function (req, res) {
    res.send('Hello World from router.js\n');
});

// curl http://127.0.0.1:3000/4/site-info
// or
// curl http://127.0.0.1:3000/post/site-info
app.get('/post/:title', function (req, res) {
    var article = req.param('title');
    if ( article != undefined && article.length > 0 ) {
        if ( isNaN(article) ) {
            // uri after post equals article title
            res.send('article title : ' + article + '\n');
        } else {
            // uri after post equals a number
            res.send('article id : ' + article + '\n');
        }
    } else {
        res.send('article request missing\n');
    }
});

HTTP-Get

var api_posts_url = 'http://toledowinter.com/api/v1/posts/site-info';

http = require('http');

http.get(api_posts_url, function(res) {
    console.log("Got response: " + res.statusCode);
    // console.dir(res);

    res.on("data", function(chunk) {
        console.log("BODY: " + chunk);
    });

}).on('error', function(e) {
    console.log("Got error: " + e.message);
});

// start server and listen on port 3000
var server = app.listen(3000, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at http://%s:%s', host, port);
});

Parse JSON

var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
console.log(obj.count);
console.log(obj.result);

For-In Loop

var p = { "p1": "value1", "p2": "value2", "p3": "value3" };

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
    }
}

Different Version of GET

http = require('http');

var options = {
    host: 'toledowinter.com',
    port: 80,
    path: '/api/v1/posts/site-info'
};

http.get(options, function(res) { console.log("Got response: " + res.statusCode); res.on("data", function(chunk) { console.log("BODY: " + chunk); obj = JSON.parse(chunk); console.log("\n formatted created date: " + obj.formatted_created_date);

    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            console.log(key + " -> " + obj[key]);
        }
    }
}); // close res.on

}).on('error', function(e) { console.log("Got error: " + e.message); }); // close http.get

From JR's : articles
1018 words - 8261 chars - 5 min read
created on
updated on - #
source - versions



A     A     A     A     A

© 2013-2017 JotHut - Online notebook

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