01 - Introduction to Node.js
01 - Introduction to Node.js
npm init
Project execution
Package.json
Modules
What is Node.Js ?
Node.js is an open-source and cross-platform JavaScript runtime environment. It is a popular tool for almost any kind of project!
Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser. This allows Node.js to be very performant.
A Node.js app runs in a single process, without creating a new thread for every request. Node.js provides a set of asynchronous I/O primitives in i
standard library that prevent JavaScript code from blocking and generally, libraries in Node.js are written using non-blocking paradigms, making blockin
behavior the exception rather than the norm.
When Node.js performs an I/O operation, like reading from the network, accessing a database or the filesystem, instead of blocking the thread an
wasting CPU cycles waiting, Node.js will resume the operations when the response comes back.
This allows Node.js to handle thousands of concurrent connections with a single server without introducing the burden of managing thread concurrenc
which could be a significant source of bugs.
Node.js has a unique advantage because millions of frontend developers that write JavaScript for the browser are now able to write the server-side cod
in addition to the client-side code without the need to learn a completely different language.
In Node.js the new ECMAScript standards can be used without problems, as you don't have to wait for all your users to update their browsers - you a
in charge of deciding which ECMAScript version to use by changing the Node.js version, and you can also enable specific experimental features b
running Node.js with flags.
It’s the perfect approach for users who need a visual map of where to go in the application. Solid, few level menu navigation is an
essential part of traditional Multi-Page Application.
Very good and easy for proper SEO management. It gives better chances to rank for different keywords since an application can be
optimized for one keyword per page.
The development becomes quite complex. The developer needs to use frameworks for either client and server side. This results in the
longer time of application development.
The LTS (Long-term Support) version is highly recommended for you. After the download of the installer package, install it with a double-click on it.
Now .msi file will be downloaded to your browser. Choose the desired location for that.
Step 2: Install Node.js and NPM
After choosing the path, double-click to install .msi binary files to initiate the installation process. Then give access to run the application.
You will get a welcome message on your screen and click the “Next” button. The installation process will start.
By clicking on the Next button, you will get a custom page setup on the screen. Make sure you choose npm package manager , not the
default of Node.js runtime . This way, we can install Node and NPM simultaneously.
You should have 143MB of space to install Node.js and npm features.
Node.js runtime
Npm package manager
Online documentation shortcuts
Add to Path
Bang! The setup is ready to install Node and NPM. Let’s click on the Install button so hard!
Step 3: Check Node.js and NPM Version
If you have a doubt whether you have installed everything correctly or not, let’s verify it with “Command Prompt”.
a CLI (command-line interface) tool for publishing and downloading packages, and
an online repository that hosts JavaScript packages
For a more visual explanation, we can think of the repository npmjs.com as a fulfillment center that receives packages of goods from sellers (np
package authors) and distributes these goods to buyers (npm package users).
To facilitate this process, the npmjs.com fulfillment center employs an army of hardworking wombats (npm CLI) who will be assigned as person
assistants to each individual npmjs.com customer. So dependencies are delivered to JavaScript developers like this:
and the process of publishing a package for your JS mates would be something like this:
Let's look at how this army of wombats assist developers who want to use JavaScript packages in their projects. We'll also see how they help ope
source wizards get their cool libraries out into the world.
package.json
Every project in JavaScript – whether it's Node.js or a browser application – can be scoped as an npm package with its own package information an
its package.json job to describe the project.
We can think of package.json as stamped labels on those npm good boxes that our army of Wombats delivers around.
package.json will be generated when npm init is run to initialise a JavaScript/Node.js project, with these basic metadata provided by developers
Downloads
npm manages downloads of dependencies of your project.
Installing all dependencies
If a project has a package.json file, by running
npm install
it will install everything the project needs, in the node_modules folder, creating it if it's not existing already.
Installing a single package
You can also install a specific package by running
Furthermore, since npm 5, this command adds <package-name> to the package.json file dependencies. Before version 5, you needed to add th
flag --save .
Often you'll see more flags added to this command:
-save-dev installs and adds the entry to the package.json file devDependencies
-no-save installs but does not add the entry to the package.json file dependencies
-save-optional installs and adds the entry to the package.json file optionalDependencies
-no-optional will prevent optional dependencies from being installed
S: --save
D: --save-dev
O: --save-optional
The difference between devDependencies and dependencies is that the former contains development tools, like a testing library, while the latter
bundled with the app in production.
YARN:
Facebook developed Yarn in 2016 as a replacement for NPM. It was designed to offer more advanced features that NPM lacked at the time (such a
version locking) and create a more secure, stable, and efficient product.
However, since Yarn was released, NPM has added several crucial features. In its current state, Yarn is now more of an alternative to NPM rather than
replacement.
Yarn version 1 and NPM both manage dependencies in a very similar way. They both store project metadata in the package.json file, located
the node_modules folder inside the project directory.
Starting from version 2, Yarn no longer uses the node_modules folder to track dependencies. Instead, Yarn 2.0 uses the Plug'n'Play feature, whic
generates a single .pnp.cjs file. This file contains a map of the dependency hierarchy for a project.
Yarn uses the yarn command to install dependencies. It installs dependencies in parallel, allowing you to add multiple files at the same time.
Installing dependencies automatically creates a lock file that saves the exact list of dependencies used for the project. With Yarn, this file
called yarn.lock.
A typical demonstration of using npx is through the cowsay command. cowsay will print a cow saying what you wrote in the command. Fo
example:
cowsay "Hello" will print
_______
< Hello >
-------
\ ^__^
\ (oo)\_______
(__)\ )\/\
w |
--w
||----
|| ||
This only works if you have the cowsay command globally installed from npm previously. Otherwise you'll get an error when you try to run th
command.
npx allows you to run that npm command without installing it first. If the command isn't found, npx will install it into a central cache:
running the vue CLI tool to create new applications and run them: npx @vue/cli create my-vue-app
creating a new React app using create-react-app : npx create-react-app my-react-app
mkdir myapp
cd myapp
npm init
Follow the command line prompt and you can leave everything as the default, then it will ask you in the end if everything looks ok.. click yes. Yo
directory should look something like this
|_myapp
|__package.json
The package.json file consists of all the project settings and other npm package dependencies. If you open the package.json it should look like this
{
"name": "myapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {"test": "echo \"Error: no test specified\" && exit 1"},
"author": "",
"license": "ISC"
}
The “name” element is the name of your package and if you upload your package to the npm registry it will be under the string that you set as the valu
of this element, in our case it’s “myapp”.
Now, create a file named index.js
Now we can safely run our project. It is as simple as running the following command
node index.js
Modules in Node.Js
In Node.js, Modules are the blocks of encapsulated code that communicates with an external application on the basis of their related functionalit
Modules can be a single file or a collection of multiples files/folders. The reason programmers are heavily reliant on modules is because of their re
usability as well as the ability to break down a complex piece of code into manageable chunks.
Modules are encapsulated code blocks that communicate with an external application. These can be a single file or a collection of multiple files/folder
These are reusable, hence they are widely used.
1. Core Modules
2. local Modules
3. Third-party Modules
The return type of require() function depends on what the particular module returns.
Http, file system and url modules are some of the core modules.
exports.add=function(n,m){
return n+m;
};
Exports keyword is used to make properties and methods available outside the file.
In order to include the add function in our index.js file we use the require function.
Code for including local modules:
Second, create an HTTP server using the createServer() method of the http object.
The createServer() accepts a callback that has two parameters: HTTP request ( req ) and response ( res ). Inside the callback, we send a
HTML string to the browser if the URL is / and end the request.
server.listen(5000);
console.log(`The HTTP Server is running on port 5000`);
server.listen(5000);
console.log(`The HTTP Server is running on port 5000`);
node server.js
Output:
Now, you can launch the web browser and go to the URL http://localhost:5000/. You’ll see the following message:
Hello, Node.js
This simple example illustrates how to use the http module. In practice, you will not use the http module directly.
Reading File
Use fs.readFile() method to read the physical file asynchronously.
Syntax:
fs.readFile(fileName [,options], callback)
Parameter Description:
var fs = require('fs');
console.log(data);
});
The above example reads TestFile.txt (on Windows) asynchronously and executes callback function when read operation completes. This read operatio
either throws an error or completes successfully. The err parameter contains error information if any. The data parameter contains the content of th
specified file.
The following is a sample TextFile.txt file.
Now, run the above example and see the result as shown below.
var fs = require('fs');
Writing File
Use fs.writeFile() method to write data to a file. If file already exists then it overwrites the existing content otherwise it creates a new file and writes da
into it.
Signature:
options: The options parameter can be an object or string which can include encoding, mode and flag. The default encoding is utf8 and
default flag is "r".
callback: A function with two parameters err and fd. This will get called when write operation completes.
The following example creates a new file called test.txt and writes "Hello World" into it asynchronously.
var fs = require('fs');
In the same way, use fs.appendFile() method to append the content to an existing file.
require(
var fs = require('fs'
'fs')
);
fs.
fs.appendFile
appendFile(
('test.txt'
'test.txt', , 'Hello World!',
World!', function (err
err)) {
err)
if (err )
console.
console.log
log((err
err));
else
console.
console.log
log(('Append operation complete.')
complete.');
});
Open File
Alternatively, you can open a file for reading or writing using fs.open() method.
Syntax:
fs.
fs.open
open(
(path
path,
, flags
flags[[, mode
mode]
], callback
callback))
Parameter Description:
callback: A function with two parameters err and fd. This will get called when file open operation completes.
Path Module:
The Node.Js Path module is a built-in module that helps you work with file system paths in an OS-independent way. The path module is essential
you’re building a CLI tool that supports OSX, Linux, and Windows.
The most commonly used function in the path module is path.join() . The path.join() function merges one or more path segments into a sing
string, as shown below.
require(
const path = require('path'
'path')
);
path.
path.join
join(
('/path'
'/path',, 'to'
'to',
, 'test.txt'
'test.txt')
); // '/path/to/test.txt'
You may be wondering why you’d use the path.join() function instead of using string concatenation.
'test.txt';
'/path' + '/' + 'to' + '/' + 'test.txt'; // '/path/to/test.txt'
'/path',
['/path', 'to'
'to',
, 'test.txt'
'test.txt']
].join
join(
('/'
'/')
); // '/path/to/test.txt'
path.
path.join(
join('data',
'data', 'test.txt')
'test.txt'); // 'data/test.txt'
path.
path.join
join(('data'
'data',
, '/test.txt'
'/test.txt')
); // 'data/test.txt'
path.
path.join
join(('data/'
'data/',, 'test.txt'
'test.txt')
); // 'data/test.txt'
path.
path.join
join(('data/'
'data/',, '/test.txt'
'/test.txt')
); // 'data/test.txt'
Parsing paths in Node
The path module also has several functions for extracting path components, such as the file extension or directory. For exampl
the path.extname() function returns the file extension as a string:
path.
path.extname
extname(
('/path/to/test.txt'
'/path/to/test.txt')
); // '.txt'
Like joining two paths, getting the file extension is trickier than it first seems. Taking everything after the last . in the string doesn’t work if there’s
directory with a . in the name, or if the path is a dotfile.
path.
path.extname
extname(
('/path/to/github.com/README'
'/path/to/github.com/README')); // ''
path.
path.extname
extname(
('/path/to/.gitignore'
'/path/to/.gitignore')
); // ''
The path module also has path.basename() and path.dirname() functions, which get the file name (including the extension) and director
respectively.
path.
path.basename
basename(
('/path/to/test.txt'
'/path/to/test.txt')); // 'test.txt'
path.
path.dirname
dirname(
('/path/to/test.txt'
'/path/to/test.txt')
); // '/path/to'
Do you need both the extension and the directory? The path.parse() function returns an object containing the path broken up into five differe
components, including the extension and directory. The path.parse() function is also how you can get the file’s name without any extension.
/*
{
root: '/',
dir: '/path/to',
base: 'test.txt',
ext: '.txt',
name: 'test'
}
*/
path.
path.parse
parse(
('/path/to/test.txt'
'/path/to/test.txt')
);
URL Module:
The URL module splits up a web address into readable parts.
require(
var url = require ('url'
'url'));
Parse an address with the url.parse() method, and it will return a URL object with each part of the address as properties:
console.
console.log
log(
(q.host
host)
); //returns 'localhost:8080'
console.
console.log
log(
(q.pathname
pathname)
); //returns '/default.htm'
console.
console.log
log(
(q.search
search)
); //returns '?year=2017&month=february'
q.
var qdata = q.query
query;; //returns an object: { year: 2017, month: 'february' }
console.
console.log
log(
(qdata
qdata..month
month)); //returns 'february'
NOTE:
Using the URL module will not let you read the URL you receive from the request. This module let you parse a URL string. If you want to read the UR
you recieve from a request in Node.Js, you have to use the HTTP module in Node.Js.
OS Module:
To use the os module, you include it as follows:
require(
const os = require('os'
'os')
);
The os module provides you with many useful properties and methods for interacting with the operating system and server.
For example, the os.EOL property returns the platform-specific end-of-line marker.
The os.EOL property returns \r\n on Windows and \n on Linux or macOS.
let currentOS = {
os.
name: os.type
type((),
os.
architecture: os .arch
arch(
(),
os.
platform: os.platform
platform((),
release: os.
os.release
release((),
os.
version: os.version(
version()
};
console.
console.log
log(
(currentOS
currentOS));
Output:
{
'Windows_NT',
name: 'Windows_NT' ,
'x64',
architecture: 'x64' ,
'win32',
platform: 'win32' ,
release: '10.0.18362',
'10.0.18362',
version: 'Windows 10 Pro'
}
console.
console.log
log(
(`The server has been up for ${
${os
os.
.uptime
uptime(
()} seconds.
seconds.``);
Output:
console.
console.log
log(
(os
os.
.userInfo
userInfo(());
Output:
{
uid: -1,
gid: -1,
username: 'john',
'john',
'C:\\Users\\john',
homedir: 'C:\\Users\\john',
shell: null
}
os.
let totalMem = os .totalmem
totalmem(
();
console.
console.log
log(
(totalMem
totalMem));
Output:
8464977920
To get the amount of free memory in bytes, you use the os.freemem() method:
os.
let freeMem = os.freemem
freemem(
();
console.
console.log
log(
(freeMem
freeMem));
Output:
1535258624
Syntax:
process.
process.argv
Return Value: This property returns an array containing the arguments passed to the process when run it in the command line. The first element is th
process execution path and the second element is the path for the js file.
require(
const process = require ('process'
'process'));
Output:
[ 'C:\\Program Files\\nodejs\\node.exe',
Files\\nodejs\\node.exe',
'C:\\nodejs\\g\\process\\argv_1.js',
'C:\\nodejs\\g\\process\\argv_1.js' ,
'extra_argument1',
'extra_argument1' ,
'extra_argument2',
'extra_argument2' ,
'3'
]
So, these are the main modules in Node.js and we will learn about some other modules in the next session.
Conclusion:
Interview Questions:
What is Node.Js and Where you can use it ?
Node.Js is an open source, cross-platform Javascript runtime environment and library to run web applications outside the client’s browser**.** It is use
to create server-side web applications.
Node.js is perfect for data-intensive applications as it uses an asynchronous, event-driven model. You can use I/O intensive web applications like vide
streaming sites. You can also use it for developing: Real-time web applications, Network applications, General-purpose applications, and Distribute
systems.
What is NPM ?
NPM stands for Node Package Manager, responsible for managing all the packages and modules for Node.js.
Provides online repositories for node.js packages/modules, which are searchable on search.nodejs.org
Provides command-line utility to install Node.js packages and also manages Node.js versions and dependencies
What are modules in Node.JS ? Name any three main modules in Node.Js.
Modules are like Javascript libraries that can be used in a Node.js application to include a set of functions. To include a module in a Node.js applicatio
use the require() function with the parentheses containing the module's name.
Node.js has many modules to provide the basic functionality needed for a web application. Some of them include:
HTTP Includes classes, methods, and events to create a Node.js HTTP server
fs Includes events, classes, and methods to deal with file I/O operations
Thank You !