How to Build a Simple Web Server with Node.js

The following is an excerpt from the book Get Programming with Node.js, published by manning.com. You can purchase the book here at a 37% discount by using the code fccwexler.
This article is a practical introduction to using Node.js. We’re going to go over installing Node.js, learn about npm, and then we’re going to build a Node.js module and jump right in to initializing a web server. Feel free to follow along at home as you read!
Installing Node.js
Node.js is growing in popularity and support. Because of this, new versions to download are being deployed quite frequently, and it’s important to stay up to date with the latest versions to see how they may benefit or otherwise impact the applications you’re building. At the time of writing, the version of Node.js to download is 7.6 or greater.
NOTE: The release of Node.js 7.6 comes with support for ES6 syntax. ES6 (ECMAScript 2015) is a recent update to JavaScript, with syntax improvements for defining variables, functions, and OOP code altogether. To keep up with updates to JavaScript, download the latest stable version of Node.js as your development progresses.
There are a couple of ways to download and install Node.js, all of which are listed on the Node.js main site.
Because Node.js is platform-independent, you can download and install it on macOS, Windows, or Linux and expect full functionality.
The simplest way to install Node.js is to go to the download link and follow the instructions and prompts to download the installer for the latest version of Node.js.
NOTE: When you install Node.js, you also get npm, the Node.js ecosystem of external libraries (multiple files of code other people wrote) that can be imported into your future projects. You’ll learn more about npm in the next section.

Figure 1. Node.js installer page
When the installer file is downloaded, double-click the file from your browser’s download panel or from your computer’s download folder. The installer will open a new window that looks like Figure 1 and write all necessary files and core Node.js libraries to your system. You may be asked to accept licensing agreements or give the installer permission to install Node.js onto your computer. Follow the prompts to click through the installation.

Figure 2. Node.js writing to your machine
Terminal and your PATH
You’ll be working mostly in your computer’s terminal, which is built-in software used to navigate and run commands on your computer without a graphical interface. This book teaches using the Unix terminal (Bash) commands. Those of you who are Windows users can follow along using Window’s CMD terminal window (you may need to look up command-equivalents throughout the book). You can reference this table comparing Windows and Unix commands. To make things easier on Windows, you can download and install an additional Bash terminal called GitBash from git-scm.com.
Make a note of where your version of Node.js and npm are installed on your machine. This information is shown in the final window in the installer. The installer attempts to add these directory locations to your system’s PATH.
Your computer’s PATH variable is the first place the terminal will look for resources used in development. Think of it like your computer’s index for quickly finding the tools you need. By adding these tools’ original file path or directory locations to the PATH variable, terminal won’t have any problems finding them. If you experience any problems starting Node.js in your terminal, follow the installation steps here.
Making sure everything’s installed correctly
Now that you have Node.js installed, let’s use terminal to make sure everything is installed correctly. Open terminal (or GitBash) and type the following command at the prompt: node-v.
The output of this command should show you the version of Node.js you’ve just installed. Similarly, you can check the version of npm that you’ve installed by running the command npm -v at the command prompt.
NOTE: If your terminal responds with an error or with nothing at all, it’s possible that your installation of Node.js was not successful. In the case of an error, try copying and pasting that error into a search engine to look for common solutions or simply try repeating the installation process.
Now that you have Node.js installed and your terminal running, you need somewhere to write your code. Although text editors come in many different forms and can be used to make non-code files as well, text editors designed specifically for developers often come prepackaged with helpful tools and plugins. I recommend installing the Atom text editor, which you can download at atom.io.
TIP: If you ever forget where you installed Node.js or npm, you can open a command window and type either which node or which npm at the prompt to see the corresponding location. From a Windows command-line prompt, use where in place of which.
Planning Your App
Imagine that you want to build an application for your city’s community-supported agriculture (CSA) club. Through this application, users could subscribe to receive food from local farms and distributors. The application ensures that your community gets healthy food and stays connected. You plan to use Node.js to build this web application and you want to start by verifying users’ zip codes to see if they live close enough for delivery. The question is: will you need to build your own tool to make this possible?
Luckily for us, the answer is no, npm can be used to install Node.js packages, libraries of code others have written that you can use to add specific features to your application. In fact, there’s a package for verifying locations based on zip codes. We’ll take a closer look at that package and how to install it in a little bit.
Creating a Node.js Module
A Node.js application is ultimately made up of many JavaScript files. For your application to stay organized and efficient, these files need to have access to each other’s contents when necessary. Each file, whose code is collectively related, is called a module. Let’s look at our app again and add some positive messages to it. You can create a file called messages.js with the following code:
let messages = [“You are great!", "You can accomplish anything!", "Success is in your future!"];

Keeping these messages separate from the code you’ll write to display them will make your code more organized. To manage these messages in another file, you need to change the let variable definition to use the exports object, like so:
exports.messages =["You are great!", "You can accomplish anything!", "Success is in your future!"];

Just like other JavaScript objects, you are adding a messages property on the Node.js exports object, which can be shared between modules.
NOTE: The exports object is actually a property of the moduleobject. module is both the name of the code files in Node.js and one of its global objects. Using exports is essentially a shorthand for module.exports.
The module is ready to be required (imported) by another JavaScript file. You can test this by creating another file called printMessages.js, whose purpose is to loop through the messages and log them to your console with the code in listing 1. First, require the local module by using the require object and the module’s filename (with or without a .js extension). Then, refer to the module’s array by the variable set up in printMessages.js.
Listing 1. log messages to console in printMessages.js
const messageModule = require(’./messages’); 1

messageModule.messages.forEach( (m) => { 2

console.log(m);

});

Require the local messages.js module.
Refer to the module’s array through messageModule.messages.

require is another Node.js global object used to locally introduce methods and objects from other modules. Node.js interprets require(‘./messages’); to look for a module called messages.js within your project directory and allow code within printMessages.js to use any properties added to the exports object.
Next, we’ll use npm, another tool for adding modules to your project.
Running npm Commands
With your installation of Node.js, you also got Node Package Manager (npm). As the name suggests, npm is responsible for managing the external packages (modules others have built and made available online) in your application. Throughout application development, npm will be used to install, remove, and modify these packages. Entering npm -l in your terminal brings up a list of npm commands with brief explanations.
Listing 2 contains a few npm commands that you’ll want to know about.
Listing 2. Npm commands to know

npm init. Initializes a Node.js application and creates a package.json file
npm install . Installs a Node.js package.
npm publish. Saves and uploads a package you built to the npm package community.
npm start. Runs your Node.js application (provided the package.json file is set up to use this command). npm stop will quit the running application.

When using the npm install <package>, appending –save to your command installs the package as a dependency for your application. Appending –global installs the package globally on your computer to be used anywhere within terminal. These command extensions, called flags, have the shorthand forms of -S and -g, respectively. npmuninstall <package> reverses the install action. Should a project call for it, the npm install express -S can be used to install the Express.js framework, and npm install express-generator -g to install the Express.js generator for use as a command-line tool.
Continue reading %How to Build a Simple Web Server with Node.js%

Link: https://www.sitepoint.com/build-a-simple-web-server-with-node-js/