4-2-Node JS
4-2-Node JS
ENVIRONMENT SETUP,
Node.js REPL TERMINAL,
NPM (NODE PACKAGE MANAGER)
CALLBACKS CONCEPT,
EVENTS,
PACKAGING,
EXPRESS FRAMEWORK,
RESTFUL API.
Introduction
◦Once you install Node.js on your computer, you can verify it by opening the command
prompt and typing node -v.
◦If Node.js is installed successfully then it will display the version of the Node.js
installed on your machine, as shown below.
◦
Node.js Console/REPL
◦ Node.js comes with virtual environment called REPL (or Node shell).
◦ REPL stands for Read-Eval-Print-Loop.
◦ It is a quick and easy way to test simple Node.js/JavaScript code.
◦ To launch the REPL (Node shell), open command prompt (in Windows) and
type node as shown below. It will change the prompt to > in Windows
Some ex: Define Variables on REPL
To exit from the REPL terminal, press Ctrl + C twice or write .exit and press Enter.
This will return back to command prompt.
The following table lists important REPL commands.
- All the modules installed using NPM are installed under node_modules folder.
- ExpressJS folder is created under node_modules folder in the root folder of our project, here in
c:\practice\NODEJS folder and install Express.js there.
--- To install ExpressJS and
also adds dependency
entry into the
package.json:
firstnjs.js
console.log("Namaste World!!!");
Node.js Basics
Primitive Types
• String
• Number
• Boolean
• Undefined
• Null
• RegExp
◦Everything else is an object in Node.js.
Loose Typing
◦Use var keyword to declare a variable of any type.
Callbacks
◦A callback is a function passed as an argument to another
function.
◦It is executed after the main function completes its task.
◦Used extensively in asynchronous programming.
◦Helps in non-blocking code execution.
Importance of Callbacks:
• Enables execution of time-consuming/heavy tasks without
stopping other operations.Faster response time.
• Efficient handling of I/O operations, file reading, network
requests, etc.
• Handles multiple tasks simultaneously, enhancing
performance.
Program: Reading a File Asynchronously
eventEmitter.on('sayHello', () => {
console.log('Hello! This is your first event in
Node.js.');
});