Node Js Sample Applications

Posted on  by admin
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.

Node.js in use - Examples

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. 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.

Technical Reasons Why Startups Choose Node.js

  • 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.
  • 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.

Main types of apps to build with Node.js

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.

log messages to console in printMessages.js. const messageModule = require(’./messages’); 1.

messageModule.messages.forEach( (m) => { 2. 1 – Require the local messages.js module. 2 – Refer to the module’s array through messageModule.messages.

Node.js applications are here to stay

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. 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.

Node.js Examples

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.

Npm commands to know. Initializes a Node.js application and creates a package.json file. npm install . Installs a Node.js package. Saves and uploads a package you built to the npm package community. Runs your Node.js application (provided the package.json file is set up to use this command).

Node.js Example Application

npm stop will quit the running application. When using the npm install , 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 reverses the install action.

Final Code Review

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.

Throughout your development with Node.js, you’ll hear the terms module and package thrown around a lot. Here’s what you need to know:. Modules are individual JavaScript files containing code that pertains to a single concept, functionality, or library.

Code the application

Packages may contain multiple modules or a single module. Packages are used to group together files offering relevant tools. “Dependencies” are Node.js modules used by an application or another module.

If a package is considered an application dependency, it must be installed (at the version specified by the application) before the application can be expected to run successfully.

Fintech apps

If there’s some functionality you’d like to incorporate into your application, there’s likely a package you can find online at npmjs.com to perform that task.

Let’s go ahead and add the ability to find where your users are located based on their zip code. To do this, we’ll need to install the cities package, built to convert text addresses into location coordinates.

NodeJS Example – INSERT entries INTO Table

However, we’re still missing one thing from this project before the package can be installed successfully. We’ll need to properly initialize a Node.js project and create a package.json file used by npm for installing cities, which we will do in the next section.

Every Node.js application or module will contain a package.json file to define the properties of that particular project. This file lives at the root level of your project. Typically, this file is where you’ll specify the version of your current release, the name of your application, and the main application file.

Node.js Example – Create a Module

This file is important for npm to save any packages to the node community online. To get started, create a folder called zip_connection, navigate to your project directory in terminal, and use the npm init command to initialize your application.

View

You’ll be prompted to fill out the name of your project, the application’s version, a short description, the name of the file from which you’ll start the app (entry point), test files, git repositories, your name (author), and a license code.

Web servers and HTTP

For now, just be sure to enter your name and press enter to accept all the default options. Once you confirm all these changes, you should see a new package.json file in your project directory resembling the contents of Listing 3.

Result of your package.json file in your zip_connection project. “name”: “zip_connection”,. “version”: “1.0.0”,. “description”: “An app to promote locally sourced food.”,.

HTML Templates

“main”: “printMessages.js”,. “test”: “echo \”Error: no test specified\” && exit 1″. “author”: “Jon Wexler”,.

“license”: “ISC”. This example package.json contains a name, version, description, starting file, custom scripts, an author, and license. Now your application has a starting point for saving and managing application configurations and packages.

Node.js Example – Create a File

You should be able to install cities by navigating to your project folder and running the following in terminal:. npm install cities –save. Also, with this installation, your project folder will have just gained a new folder called node_modules.

The code contents of the cities package you just installed lives in this folder. The –save flag will save the cities package as a dependency for this project.

Node.js Example – UPDATE Table Entries

Check your package.json file now to see how the package is listed under dependencies. Because your node_modules folder will grow in size, it is not recommended to include it when you share the project code online.

However, anyone who downloads the project can enter npm install to automatically install all the project dependencies listed in this file. Test out this new package by adding the lines in Listing 4 to main.js.

We’ll start by requiring the locally installed cities package and make it available in this file. Then we’ll use the zip_lookup method from the cities package to find a city by its zip code.

The result is stored in a variable called myCity. Implementing the cities package in main.js. const cities = require(’cities’);. var myCity = cities.zip_lookup(10016);.

Node.js Example – Using Result Object

The code above does the following:. Require the cities package. Store the resulting city from using the zip_lookup method. Log the results to your console.

The resulting data from that zip code is printed to console as shown in Listing 5. Sample result from running the main.js in terminal.

{ zipcode: ’10016’,. state_abbr: ’NY’,. latitude: ’40.746180’,. longitude: ’-73.97759’,.

IoT solutions

city: ’New York’,. state: ’New York’ }. The cities zip_lookup method returns a JavaScript object with coordinates. The tech community raves about Node.js and its use of JavaScript as a server-side language, and that’s exactly what we’re going to do now: build it!

This section covers some basic functions of the http module, a Node.js library of code used for handling requests over the internet.

Through a few short steps, you’ll convert a few lines of JavaScript into an application with which you can communicate on your web browser.

Node.js Example – Create HTTP Web Server

Web servers are the foundation of most Node.js web applications. They allow you to load images and HTML web pages to users of your app.

Let’s consider that application that we’re working on to connect users from the same zip code. Before you deliver the complete application, the community might like to see a simple site with the flexibility to improve and add features in the future.

Node.js Example – Read a File

How long do you think it will take you to build a prototype? With Node.js, you can use the http module to get a web server with sufficient functionality built within hours. Before getting started, let’s discuss some important web server concepts.

Configuration Module

After all, the final product will look and feel a lot better if you have clear expectations for the result ahead of time. A web server is software designed to respond to requests over the internet by loading or processing data.

Think of a web server like a bank teller, whose job is to process your request to deposit, withdraw, or simply view money in your account. Just as the bank teller follows a protocol to ensure that they process your request correctly, web servers follow the Hypertext Transfer Protocol (HTTP), a standardized system globally observed for the viewing of web pages and sending of data over the internet.

Example – Node.js HTTP Server

One way a client (your computer) and a server communicate is through the use of HTTP verbs. These verbs indicate what type of request is being made. For example, is the user trying to load a new web page or are they updating information in their profile page?

The context of a user’s interaction with an application is an important part of the request–response cycle.

Here are the two most widely used HTTP methods you’ll encounter:. This method is used to request information from a server. Typically, a server responds with content you can view back on your browser (e.g.

Node.js Example – Parse URL Parameters

clicking a link to see the home page of a site). This method is used to send information to the server.

A server may respond with an HTML page or redirect you to another page in the application after processing your data (e.g. filling out and submitting a sign-up form). Consider what happens when you visit google.com.

Node.js Example – Delete a File

Behind the scenes, you’re actually making a request to Google’s servers, which in turn sends a response back to you, rendering their famous “Google Search” landing page.

This request–response relationship allows for a channel of communication between the user and the application.

Notice in Figure 3 how a bundle of data is sent to the application’s server in the form of a request and, once the server processes the request, it issues a bundle of data back in the form of a response.

Get it from GitHub

This is how most of your interactions on the internet are facilitated. A web server sends your browser web pages, images and other resources on request. When you enter the URL you want to see in your browser, an HTTP request is sent to a physical computer elsewhere.

This request contains some information indicating whether you want to load a web page or send information to that computer.

You might build a fancy application with many bells and whistles, but at the core there is web server, handing its communication on the internet.

Real-time applications

These concepts will make more sense the more practice you get. For now, let’s start building our web server.

To get started with a Node.js web application, you first need to initialize the project in your project folder on terminal. Open a terminal window and create a new directory called simple_server with mkdir.

OpenID Service

You can initialize the project with npm init. npm stands for Node package manager. Your node projects rely on this tool to install and build Node.js applications. Running the npm init command initiates a prompt to create a package.json file (Figure 4).

As the prompt explains, you’ll walk through configuring the most basic settings of your Node.js application in this file.

Filling out the Node.js initializer prompts. For now, you can add main.js as the entry point, a short description, your name as the author, and elect to use the default values offered by hitting the enter key until the end of the prompt is reached.

You’ll then be asked to confirm your settings with a preview of your package.json file. Press enter to confirm and return to the regular terminal prompt.

When you installed Node.js at the beginning of this article, the core library was installed too.

Within that library is a module called http, which we talked about earlier.