You're viewing old version number 4. - Current version
1 min
Node.js code snippets
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;
From JR's : articles
317 words - 2568 chars
- 1 min read
created on
updated on
- #
source
- versions