This draft deletes the entire topic.
Examples
-
First, install Node.js for your platform.
Create a HTTP server listening on port 1337, which sends
Hello, World!
to the browser.The
http
module provides the functionality to create a HTTP server using thehttp.createServer()
method. To create the application, create a file containing the following JavaScript code.const http = require('http'); http.createServer((req, res)=>{ // 1. Tell the browser everything is OK, and the data is in plain text. res.writeHead(200, { 'Content-Type': 'text/plain' }); // 2. Send the announced text. res.end('Hello, World!\n'); }).listen(1337);
Save the file with any file name. In this case, if we name it
hello.js
we can run the application using the following command:node hello.js
The created server can then be accessed with the URL http://localhost:1337 or http://127.0.0.1:1337 in the browser.
A simple web page will appear with a “Hello, World!” text at the top, as shown in the screenshot below.
-
Node.js can also be used to create command line utilities. The code below reads a string from the command line argument to print a Hello message.
To run this code:
- Create an empty file, and paste the code below. The name of the file isn't important but many people will name this file app.js or main.js.
- Change the permission of the file to make it an executable. Example
chmod 700 FILE_NAME
- Run the app by typing
./APP_NAME
#!/usr/bin/env node 'use strict'; /* The process.argv property returns an array containing the command line arguments passed when the Node.js process was launched. The first element will be process.execPath. The second element will be the path to the JavaScript file being executed. The remaining elements will be any additional command line arguments. Example: [ 'node', '/path/to/yourscript', 'arg1', 'arg2', ... ] URL: https://nodejs.org/api/process.html#process_process_argv */ // 1. Extract the name of the app/file name. let appName = process.argv[1].split('/').pop(); // 2. Save the first provided argument as the username. let name = process.argv[2]; // 3. Check if the name was provided. if(!name) { // 1. Give the user an example how to use the app. console.log("Missing argument! \n\n\tExample: %s YOUR_NAME\n", appName) // -> Exit the app if error. The nr 1 tels the system that the app quit // with an error, thus another command won't be executed. For example: // ./hello $$ ls -> won't execute ls // ./hello David $$ ls -> will execute ls process.exit(1) } // 4. Display the message in the console. console.log('Hello, %s!', name);
-
-
The following example uses Express to create an HTTP server listening on port 3000, which responds with "Hello, World!".
var express = require('express'); var app = express(); app.get('/', function (req, res) { res.send('Hello, World!'); }); app.set('port', (process.env.PORT || 3000)); app.listen(app.get('port'), function () { console.log('Example app listening on port 3000!'); });
For more information about the Express framework, you can check the Web Apps With Express section
-
Installation
First, install Node.js on your development computer.
Windows: Go to the Node.js download site and download/run the installer.
Mac: Go to the Node.js download site and download/run the installer. Alternativily you can also install node via homebrew
brew install nvm
orbrew install node
homebrew allows you to manage packages via the command line read more about it on the (homebrew site)[http://brew.sh/]Linux: Follow the instructions for your distro on the command line installation page.
Running a Node Program
To run a NodeJS program, simply run
node app.js
ornodejs app.js
, whereapp.js
is the filename of your node app source code.Alternatively, a node program may be executed as a script. To do so, it needs to begin with a shebang pointing to the node interpreter, e.g.
#!/usr/bin/env node
. Then, the file has to be set as executable. Now the script can be directly run from the command line. -
You can use the node-inspector. Run this command to install it via npm:
npm install -g node-inspector
Then you can debug your application using
node-debug app.js
The Github repository can be found here: https://github.com/node-inspector/node-inspector
-
When called without arguments, Node.js starts a REPL (Read-Eval-Print-Loop) also known as the “Node shell”.
At a command prompt type
node
.$ node >
At the Node shell prompt
>
type "Hello World!"$ node > "Hello World!" 'Hello World!'
-
Once you understand how to create an HTTP Server with node, it's important to understand how to make it "do" things based on the path that a user has navigated to. This phenomenon is called, "routing".
The most basic example of this would be to check
if (request.url === 'some/path/here')
, and then call a function that responds with a new file.An example of this can be seen here:
var http = require('http'); function index (request, response) { response.writeHead(200); response.end('Hello, World!'); } http.createServer(function (request, response) { if (request.url === '/') { return index(request, response); } response.writeHead(404); response.end(http.STATUS_CODES[404]); }).listen(1337);
If you continue to define your "routes" like this, though, you'll end up with one massive callback function, and we don't want a giant mess like that, so let's see if we can clean this up.
First, let's store all of our routes in an object:
var routes = { '/': function index (request, response) { response.writeHead(200); response.end('Hello, World!'); }, '/foo': function foo (request, response) { response.writeHead(200); response.end('You are now viewing "foo"'); } }
Now that we've stored 2 routes in an object, we can now check for them in our main callback:
http.createServer(function (request, response) { if (request.url in routes) { return routes[request.url](request, response); } response.writeHead(404); response.end(http.STATUS_CODES[404]); }).listen(1337);
Now every time you try to navigate your website, it will check for the existence of that path in your routes, and it will call the respective function. If no route is found, the server will respond with a 404 (Not Found).
And there you have it--routing with the HTTP Server API is very simple.
-
The only major differences between this and a regular TCP connection are the private Key and the public certificate that you’ll have to set into an option object.
How to Create a Key and Certificate
The first step in this security process is the creation of a private Key. And what is this private key? Basically, it's a set of random noise that's used to encrypt information. In theory, you could create one key, and use it to encrypt whatever you want. But it is best practice to have different keys for specific things. Because if someone steals your private key, it's similar to having someone steal your house keys. Imagine if you used the same key to lock your car, garage, office, etc.
openssl genrsa -out private-key.pem 1024
Once we have our private key, we can create a CSR (certificate signing request), which is our request to have the private key signed by a fancy authority. That is why you have to input information related to your company. This information will be seen by the signing authority, and used to verify you. In our case, it doesn’t matter what you type, since in the next step we're going to sign our certificate ourselves.
openssl req -new -key private-key.pem -out csr.pem
Now that we have our paper work filled out, it's time to pretend that we're a cool signing authority.
openssl x509 -req -in csr.pem -signkey private-key.pem -out public-cert.pem
Now that you have the private key and the public cert, you can establish a secure connection between two NodeJS apps. And, as you can see in the example code, it is a very simple process.
Important!
Since we created the public cert ourselves, in all honesty, our certificate is worthless, because we are nobodies. The NodeJS server won't trust such a certificate by default, and that is why we need to tell it to actually trust our cert with the following option rejectUnauthorized: false. Very important: never set this variable to true in a production environment.
TLS Socket Server
'use strict'; let tls = require('tls'); let fs = require('fs'); const PORT = 1337; const HOST = '127.0.0.1' let options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem') }; let server = tls.createServer(options, function(socket) { // Send a friendly message socket.write("I am the server sending you a message."); // Print the data that we received socket.on('data', function(data) { console.log('Received: %s [it is %d bytes long]', data.toString().replace(/(\n)/gm,""), data.length); }); // Let us know when the transmission is over socket.on('end', function() { console.log('EOT (End Of Transmission)'); }); }); // Start listening on a specific port and address server.listen(PORT, HOST, function() { console.log("I'm listening at %s, on port %s", HOST, PORT); }); // When an error occurs, show it. server.on('error', function(error) { console.error(error); // Close the connection after the error occurred. server.destroy(); });
TLS Socket Client
'use strict'; let tls = require('tls') let fs = require('fs'); const PORT = 1337; const HOST = '127.0.0.1' // Pass the certs to the server and let it know to process even unauthorized certs. let options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'), rejectUnauthorized: false }; let client = tls.connect(PORT, HOST, options, function() { // Check if the authorization worked if (client.authorized) { console.log("Connection authorized by a Certificate Authority."); } else { console.log("Connection not authorized: " + client.authorizationError) } // Send a friendly message client.write("I am the client sending you a message."); }); client.on("data", function(data) { console.log('Received: %s [it is %d bytes long]', data.toString().replace(/(\n)/gm,""), data.length); // Close the connection after receiving the message client.end(); }); client.on('close', function() { console.log("Connection closed"); }); // When an error ocoures, show it. client.on('error', function(error) { console.error(error); // Close the connection after the error occurred. client.destroy(); });
-
When you deploy your app online (for example, Heroku), you will need to change the port number to
process.env.PORT
. This allows you to access the application.For example,
http.createServer(function(req, res) { // your server code }).listen(process.env.PORT);
Also, if you would like to access this offline while debugging, you can use this:
http.createServer(function(req, res) { // your server code }).listen(process.env.PORT || 3000);
where
3000
is the offline port number. -
-
var net = require('net'); // Creates a TCP server. var server = net.createServer(function (socket) { console.log("Connection from " + socket.remoteAddress); socket.end("Hello World\n"); }); server.listen(8000, "localhost"); console.log("TCP server listening on port 8000 at localhost.");
Remarks
Node.js is an event-based, non-blocking, asynchronous I/O framework that uses Google's V8 JavaScript engine. It is used for developing applications that make heavy use of the ability to run JavaScript both on the client, as well as on server side and therefore benefit from the re-usability of code and the lack of context switching.
Versions
Version | Release Date |
---|---|
v7.0.0 | 2016-10-25 |
v6.9.1 | 2016-10-19 |
v6.9.0 | 2016-10-18 |
v6.8.1 | 2016-10-14 |
v6.8.0 | 2016-10-12 |
v6.7.0 | 2016-09-27 |
v6.6.0 | 2016-09-14 |
v6.5.0 | 2016-08-26 |
v6.4.0 | 2016-08-12 |
v6.3.1 | 2016-07-21 |
v6.3.0 | 2016-07-06 |
v6.2.2 | 2016-06-16 |
v6.2.1 | 2016-06-02 |
v6.2.0 | 2016-05-17 |
v6.1.0 | 2016-05-05 |
v6.0.0 | 2016-04-26 |
v5.12.0 | 2016-06-23 |
v5.11.1 | 2016-05-05 |
v5.11.0 | 2016-04-21 |
v5.10.1 | 2016-04-05 |
v5.10 | 2016-04-01 |
v5.9 | 2016-03-16 |
v5.8 | 2016-03-09 |
v5.7 | 2016-02-23 |
v5.6 | 2016-02-09 |
v5.5 | 2016-01-21 |
v5.4 | 2016-01-06 |
v5.3 | 2015-12-15 |
v5.2 | 2015-12-09 |
v5.1 | 2015-11-17 |
v5.0 | 2015-10-29 |
v4.4 | 2016-03-08 |
v4.3 | 2016-02-09 |
v4.2 | 2015-10-12 |
v4.1 | 2015-09-17 |
v4.0 | 2015-09-08 |
io.js v3.3 | 2015-09-02 |
io.js v3.2 | 2015-08-25 |
io.js v3.1 | 2015-08-19 |
io.js v3.0 | 2015-08-04 |
io.js v2.5 | 2015-07-28 |
io.js v2.4 | 2015-07-17 |
io.js v2.3 | 2015-06-13 |
io.js v2.2 | 2015-06-01 |
io.js v2.1 | 2015-05-24 |
io.js v2.0 | 2015-05-04 |
io.js v1.8 | 2015-04-21 |
io.js v1.7 | 2015-04-17 |
io.js v1.6 | 2015-03-20 |
io.js v1.5 | 2015-03-06 |
io.js v1.4 | 2015-02-27 |
io.js v1.3 | 2015-02-20 |
io.js v1.2 | 2015-02-11 |
io.js v1.1 | 2015-02-03 |
io.js v1.0 | 2015-01-14 |
v0.12 | 2016-02-09 |
v0.11 | 2013-03-28 |
v0.10 | 2013-03-11 |
v0.9 | 2012-07-20 |
v0.8 | 2012-06-22 |
v0.7 | 2012-01-17 |
v0.6 | 2011-11-04 |
v0.5 | 2011-08-26 |
v0.4 | 2011-08-26 |
v0.3 | 2011-08-26 |
v0.2 | 2011-08-26 |
v0.1 | 2011-08-26 |
Topic Outline
- Hello World HTTP server
- Hello World command line
- Hello World with Express
- Installation and running program
- Debugging Your NodeJS Application
- Hello World in the REPL
- Hello World basic routing
- TLS Socket: server and client
- Deploying your application online
- Hello World on standard output
- TCP server
Versions
Sign up or log in
Save edit as a guest
Join Stack Overflow
Using Google
Using Facebook
Using Email and Password
We recognize you from another Stack Exchange Network site!
Join and Save Draft