You're viewing old version number 12. - Current version
4 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;
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
From JR's : articles
731 words - 5827 chars
- 4 min read
created on
updated on
- #
source
- versions