Create Your First Website With Nodejs

Create Your First Website With Nodejs

Node.js is a run time platform to run server-side apps in JavaScript. It adopted the V8 browser engine to interpret JavaScript code on the server.

Node.js is a run time platform to run server-side apps in JavaScript. It adopted the V8 browser engine to interpret JavaScript code on the server. It comes with its own set of built-in modules in its standard library for running server-side apps and allows for interaction with hardware directly.

It can let us manipulate files and do many things on a computer. It’s different from JavaScript in the browser since it does completely different things. One of the things Node.js can do is run a webserver to serve static and dynamic content.

In this article, we will get acquainted with Node.js by installing the Node.js run time platform and build simple web apps with it. We begin by downloading the Node.js run time.

To do this on Windows, we go to https://nodejs.org/en/ and click the LTS link to download the Node.js run time and then double-click on the downloaded executable and follow the instructions. In Linux, we can use a package manager to download Node.js.

Each distribution will have a different way to download the Node.js run time. For example, in Ubuntu, we run the following commands to download Node.js:

$ sudo apt-get install curl
$ curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
$ sudo apt-get install nodejs

When we run the commands above, we download the Node.js LTS version and install it. Then, we can run:

$ node -v

To check the version of Node.js that’s installed.

After Node.js run time is installed, we have to learn how to use the terminal.

On Windows, we will use the Node.js command prompt which is installed when we installed Node.js with the instructions above. The special command prompt has the Node.js environment already set up for us, while the regular command prompt does not.

Therefore, we need the Node.js command prompt to run Node.js apps. Windows 10 also has the Windows Subsystem for Linux, which provides us with different flavors of Linux as a command prompt program to let us do many things that can be done on Linux in Windows.

To install it, we have to go to the start menu and search for Turn Windows Features on and off, and then choose Windows Subsystem for Linux and click OK. After that, restart your computer.

Then, after you’ve restarted, go to the Windows App Store and search for the Linux flavor that you want. The most common one is Ubuntu, so we can search for that and click Install.

After that, open the Ubuntu command prompt program that’s installed and let it run, then it will prompt you to create an account by setting a username and password for logging into the command prompt.

With the Windows Subsystem for Linux, the disk storage is shared with Windows, so we don’t have to worry about moving files around.

However, disk operations for version 1 of the Windows Subsystem for Linux are slow. Version 2 is much faster and will be out with the latest update of Windows 10.

For macOS and Linux users, they have terminal programs that let us run commands in the command prompt. It doesn’t need a special command prompt program to run Node.js apps. They both can run POSIX compliant programs.

An alternative for all users is to use a virtual machine for running Node.js on the operating system of your choice.

One popular choice is to use VirtualBox, which has support for many common operating systems like Windows and many flavors of Linux. It’s free and it’s supported by a big community.

Installing a new operating system on a VirtualBox virtual machine is easy and there are pre-made virtual machines available for download. For example, https://www.osboxes.org/ has many Linux virtual machines made for VirtualBox.

Virtual machines use their own storage and share memory with the host machine, so virtual machines will take a significant chunk of memory that you set aside when you set up the virtual machine.

If you don’t like how virtual machines interact with your own keyboard, you can improve the experience by using a terminal program like PuTTY to connect to it.

However, you have to enable your virtual machine before doing this. For instance, to enable login from PuTTY to your VirtualBox virtual machine, we have to do the following steps:

  • Run sudo apt install ssh to install the SSH programs.
  • Turn off the virtual machine.
  • In VirtualBox, go to the Settings menu, Network section. On Adapter 1 choose Host-only adapter, then click OK.
  • Start your VirtualBox virtual machine, log in, and run ifconfig to get the IP address of your virtual machine.
  • Then, you can use that to log into the terminal program of your choice, like PuTTY.

After setting up Node.js on your virtual machine or computer, we can start writing Node.js programs. First, we have to use a text editor to write programs because we need a program that only saves plain text, which is what code is.

For example, in Windows, Visual Studio Code is a great choice for writing JavaScript code. It has autocompletion for code and modules you’re trying to type in code to reference them.

Also, it’s fast and lightweight. It only takes 250MB of disk space and requires 1GB of memory and a 1.6 GHz processor.

These requirements are comparable to other text editors that are feature-rich. It also has settings for zoom, splitting the view of a single file, recognizes different types of files so that they can be highlighted properly for easy reading, and it has many add-ons to extend its functionality.

It also integrates with the command prompt or shell of your computer’s operating system so you can run commands directly in it.

JavaScript support is built-in, so we get syntax highlighting, autocomplete, and catching syntax errors automatically for JavaScript code. This is very helpful for increasing the productivity of programming with JavaScript since it helps reading and writing the code faster. It’s also built with JavaScript.

To make useful programs, we have to use other libraries to help us achieve this as we can’t write everything ourselves. Node.js has a standard library that lets us to many things like run a web server and manipulate files stored on the computer.

To do things that aren’t in the standard library, we can install Node.js packages and import or require them in your app’s code. Libraries are stored in package repositories and can be downloaded by a package manager.

For the Node.js ecosystem, the most popular package repository is the Node Package Manager or npm. Npm is a repository for Node.js packages and we can download them with the npm program.

The npm program has many commands that let us download Node.js packages easily. The details of the packages you installed are stored in package.json in the project folder you’re in.

package.json can also store commands for scripts in the scripts section for package.json.

Also, to prevent package versions from changing and causing problems, a package-lock.json is created, indicating the version that’s installed when you install a package. If you use version control, you will check in both files so you get the right packages installed when you set up your app again.

Npm has many commands to do things to Node packages. The most common ones are below.

npm install

npm install, or npm i for short, is used to install packages.

If you don’t put a package name after install, it downloads all the packages listed in package.json if the dependencies aren’t installed yet or the version installed is outdated.

If you put a package name after npm install, it will install the package with that name as long as it finds the package. During the installation process, npm will run npm run link and npm run build to compile the packages.

You can install packages globally by running npm install -g packageName.

npm prune

npm prune removes unused packages. npm run --production is used to delete packages from the devDependencies section. The --dry-run option is used for checking which packages will be deleted before the actual run.

The --json option can be used to display results in JSON. With package-lock enabled, pruning is automatic.

npm run

npm run-script lets you run custom scripts that you’ve written. npm run is an alias of this command.

npm start

npm start starts a package by running the command you define.

npm update

npm update updates packages in the project. npm update packageName updates only the package with the name packageName. It will record the latest version to package-lock.json.

To install npm or upgrade npm to the latest version, run npm install -g npm.

Creating a Web Server

Now we have everything we need to write a basic web server. All it does it to serve the “Hello World” response by listening to the given port. We can view the message by going to the localhost with the given port.

What a web server does is, when given the URL that you put into the browser or an HTTP client, it gets the request you made, including URL, headers, cookies, and the request body, and then the server will do something in according to the request accepted.

The web server will get the request data like the URL, request method (GET, POST, PATCH, PUT, DELETE), headers, cookies, and the request body, and make the response according to the data in the request.

For example, if we go to http://localhost:9999/helloworld, then the webserver that listens to the port 9999 will get the request URL, and then if the URL is helloworld, which in this case it is, it will return the plain text response “Hello world”.

The response can have its own headers like file type and body data. It can be in different formats like plain text or JSON, which is plain text that has a format that looks like a JavaScript literal.

Also, the response will have a response code. The response code ranges from 100 to 500. Common ones include 200 for a generic success response, 201 for new data created, and 204 for responding with no content.

300 series responses are for redirect responses. 301 stands for moved permanently. 302 means resources are found. 400 series errors are for errors on the client-side.

For example, 400 is the generic bad request response for times when bad data is submitted to the server. 401 is for an unauthorized response when a user fails to log in with the correct credentials.

Typically, 403 is returned when a resource that’s not allowed to be accessed by the user is attempted to be accessed. 404 is a resource not found response.

405 is for making a request using an HTTP method that’s not authorized. 422 is another response that’s returned for sending bad data and can’t be processed by the server.

500 series errors are server-side errors. 500 is for generic server error. 502 is for a bad gateway, 503 indicates that service is unavailable, 504 is for gateway timeout.

Now we can write our web server with Node.js.

We will do it in two ways. We will use the http module that’s built into Node.js and the very popular Express web framework for building our web server app.

The one built with the http module looks like the following:

const http = require("http");
http
  .createServer((request, response) => {
    response.writeHead(200, { "Content-Type": "text/plain" });
    response.write("Hello, World!");
    response.end();
  })
  .listen(8888);
console.log("Server listening on port 8888");

In the code above, we first import the http modules with the const http = require(“http”); line. Then, we used the createServer function to create the HTTP server.

Then, we pass in a callback function, which takes a request and response parameter. This is handy for processing data given the request that was taken in by the server. For this simple “Hello World” example, we just return the response.

We set the header with the writeHead function, available in the response object and set the response code, which is 200 for a successful response, and the Content-Type response header, which is set to text/plain since we want to return plain text.

Then, we run the response.write function with the “Hello, World!” string to display “Hello world” in the browser of the HTTP client of your choice. Calling response.end() will return the response to the browser of the HTTP client.

We can run the app by saving the code above in a file called app.js in the directory of your choice then running node app.js after going into the directory that you saved the file to. After that, we should see:

The code above is OK for very simple apps like the Hello World app. However, when an app has more functionality, writing them using the http module would be a pain.

We would have to check the request and response in the listener, then we have checked the URLs that we want the users to go to and then manipulate the response and return it according to the things passed into the request object.

This is going to make creating complex apps difficult where there are lots of URLs that you want to check with different variations of headers and bodies in the request.

Therefore, we can use a framework to make this simpler. The Express framework is very simple and easy to use and lets us simplify our Hello World app.

To build our app with Express, we can create a folder, then go into the folder and run npm init -y.

This creates an empty package.json file that designates the folder as a Node.js project folder. Run npm i express to install the Express framework. Create app.js in the same folder and add:

const express = require("express");
const app = express();
const port = 9999;
app.get("/", (req, res) => {
  res.send("Hello, World!");
});
app.listen(port, function() {
  console.log(`Server listening on port ${port}`);
});

We can run it by running node app.js in the folder you created and going to http://localhost:9999, where you would see the same thing as we have above.

It only displays “Hello World” when you go to http://localhost:9999. Other URLs like http://localhost:9999/abc won’t work as we only specified that the root URL, denoted by “/”, will return “Hello World!”

This is one thing that we don’t have in the webserver where we used the http module.

Node.js is a run time platform that has a great ecosystem. It adopted the V8 browser engine to interpret JavaScript code on the server.

It comes with its own set of built-in modules in its standard library for running server-side apps and allows for interaction with hardware directly.

It lets us manipulate files and do many things on a computer. It’s different from JavaScript in the browser since it does completely different things.

Creating a simple web server can be done simply with the http module built into the standard library of Node.js or we can use the Express framework for more advanced functionality.

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step) - Learn the basics of Node.js. This Node.js tutorial will guide you step by step so that you will learn basics and theory of every part. Learn to use Node.js like a professional. You’ll learn: Basic Of Node, Modules, NPM In Node, Event, Email, Uploading File, Advance Of Node.

Node.js for Beginners

Learn Node.js from Scratch (Step by Step)

Welcome to my course "Node.js for Beginners - Learn Node.js from Scratch". This course will guide you step by step so that you will learn basics and theory of every part. This course contain hands on example so that you can understand coding in Node.js better. If you have no previous knowledge or experience in Node.js, you will like that the course begins with Node.js basics. otherwise if you have few experience in programming in Node.js, this course can help you learn some new information . This course contain hands on practical examples without neglecting theory and basics. Learn to use Node.js like a professional. This comprehensive course will allow to work on the real world as an expert!
What you’ll learn:

  • Basic Of Node
  • Modules
  • NPM In Node
  • Event
  • Email
  • Uploading File
  • Advance Of Node

Top 7 Most Popular Node.js Frameworks You Should Know

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser.

One of the main advantages of Node is that it enables developers to use JavaScript on both the front-end and the back-end of an application. This not only makes the source code of any app cleaner and more consistent, but it significantly speeds up app development too, as developers only need to use one language.

Node is fast, scalable, and easy to get started with. Its default package manager is npm, which means it also sports the largest ecosystem of open-source libraries. Node is used by companies such as NASA, Uber, Netflix, and Walmart.

But Node doesn't come alone. It comes with a plethora of frameworks. A Node framework can be pictured as the external scaffolding that you can build your app in. These frameworks are built on top of Node and extend the technology's functionality, mostly by making apps easier to prototype and develop, while also making them faster and more scalable.

Below are 7of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Express

With over 43,000 GitHub stars, Express is the most popular Node framework. It brands itself as a fast, unopinionated, and minimalist framework. Express acts as middleware: it helps set up and configure routes to send and receive requests between the front-end and the database of an app.

Express provides lightweight, powerful tools for HTTP servers. It's a great framework for single-page apps, websites, hybrids, or public HTTP APIs. It supports over fourteen different template engines, so developers aren't forced into any specific ORM.

Meteor

Meteor is a full-stack JavaScript platform. It allows developers to build real-time web apps, i.e. apps where code changes are pushed to all browsers and devices in real-time. Additionally, servers send data over the wire, instead of HTML. The client renders the data.

The project has over 41,000 GitHub stars and is built to power large projects. Meteor is used by companies such as Mazda, Honeywell, Qualcomm, and IKEA. It has excellent documentation and a strong community behind it.

Koa

Koa is built by the same team that built Express. It uses ES6 methods that allow developers to work without callbacks. Developers also have more control over error-handling. Koa has no middleware within its core, which means that developers have more control over configuration, but which means that traditional Node middleware (e.g. req, res, next) won't work with Koa.

Koa already has over 26,000 GitHub stars. The Express developers built Koa because they wanted a lighter framework that was more expressive and more robust than Express. You can find out more about the differences between Koa and Express here.

Sails

Sails is a real-time, MVC framework for Node that's built on Express. It supports auto-generated REST APIs and comes with an easy WebSocket integration.

The project has over 20,000 stars on GitHub and is compatible with almost all databases (MySQL, MongoDB, PostgreSQL, Redis). It's also compatible with most front-end technologies (Angular, iOS, Android, React, and even Windows Phone).

Nest

Nest has over 15,000 GitHub stars. It uses progressive JavaScript and is built with TypeScript, which means it comes with strong typing. It combines elements of object-oriented programming, functional programming, and functional reactive programming.

Nest is packaged in such a way it serves as a complete development kit for writing enterprise-level apps. The framework uses Express, but is compatible with a wide range of other libraries.

LoopBack

LoopBack is a framework that allows developers to quickly create REST APIs. It has an easy-to-use CLI wizard and allows developers to create models either on their schema or dynamically. It also has a built-in API explorer.

LoopBack has over 12,000 GitHub stars and is used by companies such as GoDaddy, Symantec, and the Bank of America. It's compatible with many REST services and a wide variety of databases (MongoDB, Oracle, MySQL, PostgreSQL).

Hapi

Similar to Express, hapi serves data by intermediating between server-side and client-side. As such, it's can serve as a substitute for Express. Hapi allows developers to focus on writing reusable app logic in a modular and prescriptive fashion.

The project has over 11,000 GitHub stars. It has built-in support for input validation, caching, authentication, and more. Hapi was originally developed to handle all of Walmart's mobile traffic during Black Friday.

Node JS Full Course Learn Node.js in 7 Hours

Node JS Full Course Learn Node.js in 7 Hours

This Edureka Node.js Full Course video will help you in learn Node.js along with practical demonstration. This Node.js Tutorial for Beginners is ideal for both beginners as well as professionals who want to master the most prominently used javascript backend framework.

This Edureka Node.js Full Course video will help you in learn Node.js along with practical demonstration. This Node.js Tutorial for Beginners is ideal for both beginners as well as professionals who want to master the most prominently used javascript backend framework. Below are the topics covered in this node.js tutorial video:
2:32 What is Node.js?
3:22 Client-Server Architecture
4:12 Multi-Threaded Model
6:13 Single-Threaded Model
7:43 Multi-Threaded vs Event-Driven
9:45 Uber Old Architecture
11:10 Uber New Architecture
12:30 What is Node.js?
13:05 Sucess Stories
14:20 Node.js Trend
14:40 Node.js Features
16:25 Node.js Installation
16:50 Node.js First Example
17:30 Blocking vs Non-blocking
18:50 Demo
23:50 Node.js Modules
23:50 NPM
25:10 Global Objects
26:55 File System
30:30 Callbacks
31:45 Event
33:05 HTTP
34:50 Hands On
1:09:45 Node.js Tutorial
1:10:45 What is Node.js?
1:12:10 Features of Node.js
1:13:00 Node.js Architecture
1:14:55 NPM(Node Package Manager)
1:16:20 Node.js Modules
1:16:30 Node.js Modules Types
1:16:35 Core Modules
1:16:55 Local Modules
1:17:10 3rd Party Modules
1:18:35 JSON File
1:23:30 Data Types
1:25:35 Variables
1:26:40 Operators
1:27:45 Functions
1:29:10 Objects
1:29:55 File Systems
1:33:50 Events
1:34:20 HTTP Module
1:40:02 Events
1:44:37 HTTP Module
1:45:27 Creating a Web Server using Node.js
1:45:42 Express.js
1:46:57 Demo
1:58:37 Node.js NPM Tutorial
1:59:37 What is NPM?
2:03:12 Main Functions of NPM
2:04:27 Need For NPM
2:08:07 NPM Packages
2:17:42 NPM Installation
2:18:12 JSON File
2:31:32 Node.js Express Tutorial
2:32:02 Introduction to Express.js
2:32:32 Features of Express.js
2:35:27 Getting Started with Express.js
2:39:42 Routing Methods
2:44:57 Hands-On
2:48:12 Building RESTful API with Node.js
2:48:27 What is REST API?
2:49:42 Features of REST API
2:51:12 Principles of REST API
2:56:37 Methods of REST API
2:59:52 Building REST API with Node.js
3:24:07 Node.js MySQL Tutorial
3:24:32 What is MySQL?
3:25:13 Advantages of Using MySQL with Node.js
3:27:38 MySQL Installation
3:44:23 Node.js MongoDB Tutorial
3:44:58 What is NoSQL?
3:47:53 NoSQL Databases
3:48:38 Introduction to MongoDB
3:52:48 Features of MongoDB
3:53:03 MongoDB Installation
4:36:08 Node.js Docker Tutorial
4:36:38 What is Docker?
4:39:13 Docker Working
4:41:43 Docker Basics
4:41:48 DockerFile
4:42:03 Docker Images
4:42:23 Docker Container
4:44:38 Why use Node.js with Docker?
4:45:18 Demo: Node.js with Docker
4:58:38 MEAN Stack Application Tutorial
4:59:18 What is MEAN Application?
4:59:53 MongoDB
5:00:28 Express
5:01:13 Angular
5:01:23 Node.js
5:02:17 RESTful API
5:03:02 Contact List MEAN App
6:17:57 Node.js Interview Questions

Got a question on the topic? Please share it in the comment section below and our experts will answer it for you.