Node.js Hello World


Running your first Node.js application in Windows is very easy. Once you have successfully installed Node.js you can create a JavaScript file with one line of code in it and run that file from the Windows command prompt.

Here is your JavaScript file below called hello.js. Use your favorite text editor to create it. For something this simple I like to use the application called Notepad++. Save it in a directory on your computer.

hello.js

console.log('Node is running! A message from hello.js written by me.');
console.log('A follow-up message on another console log statement.');

Save this file in a directory on your hard drive, such as C:\Sites\HelloJS, or wherever you wish. I chose to use a short path to the file because I need to navigate to the directory in the command prompt using the cd command. Shorter paths are easier to navigate to.

Server

Just to show what else Node can do, here is some code to run a server. This code is from the book The Node Beginner Book by Manuel Kiessling.

var http = require("http");

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(8888);

Same as before, create a new file with the above contents in a new folder and run it with node, then open it in the browser. To explain in a bit more detail, first create a new directory called C:\Sites\HelloFromServer. Next create a text file called server.js and put in in that folder. Add the above code and save it. Navigate to the directory in your command prompt. Type node server.js. You won’t see anything happen in your command prompt but open a browser window and go to this address: http://localhost:8888/

You should see Hello World at the top left of your browser window. You just wrote a working HTTP server!

To shut down the Node server, go to the command prompt. Type Ctrl+C if you are using Windows.

Angular 2 Development Environment

To set up a full development environment for Angular 2, please follow the instruction at the post Angular 2 Installation Introduction.

Leave a comment

Your email address will not be published. Required fields are marked *