Hello World in node.js
A simple print statement that prints “Hello World!”
[code language=”javascript”]
console.log("Hello World!");
[/code]
A node js http server that prints “Hello World!” to all requests.
[code language=”javascript”]
// Load the http module to create an http server.
var http = require(‘http’);
// Configure the HTTP server to print 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 1234
server.listen(1234);
console.log(‘You will see "Hello World!"" if you open up a browser and go to the url http://localhost:1234/’);
[/code]
A node js tcp server that prints “Hello World!” to all requests.
[code language=”javascript”]
// Load the net module to create a tcp server.
var net = require(‘net’);
// Create a new TCP server.
var server = net.createServer(function (socket) {
console.log("Connection from " + socket.remoteAddress);
socket.end("Hello World!\n"); //Print Hello World! to all requests.
});
// Listen to port 9123 on localhost
server.listen(9123, "localhost");
// Put a friendly message on the terminal
console.log("You can connect go to http://localhost:9123 or issue one of these commands on your terminal");
console.log("curl http://localhost:9123");
console.log("nc localhost 9123");
console.log("netcat localhost 9123");
[/code]
Assume you have node installed and you’ve created 3 js files for the above 3 programs. You can run them by these commands
[code language=”shell”]
node helloworld.js
node helloworld_http_server.js
node helloworld_tcp_server.js
[/code]
Search within Codexpedia
Search the entire web