[Go to site: main page, start]

0% found this document useful (0 votes)
248 views8 pages

Node.js Overview and Key Concepts

Node.js is a JavaScript runtime environment that allows JavaScript to be run outside of a browser. It was created using the Chrome V8 JavaScript engine and built on top of it. Node.js is event-driven and non-blocking, using asynchronous programming. It includes various built-in modules for file systems, streams, networking and more. Express.js is a popular web framework for Node.js that allows setting up middleware functions to handle requests and responses. Middleware functions have access to the request, response and next objects and can send responses directly without needing to call controllers.

Uploaded by

Vannila
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
248 views8 pages

Node.js Overview and Key Concepts

Node.js is a JavaScript runtime environment that allows JavaScript to be run outside of a browser. It was created using the Chrome V8 JavaScript engine and built on top of it. Node.js is event-driven and non-blocking, using asynchronous programming. It includes various built-in modules for file systems, streams, networking and more. Express.js is a popular web framework for Node.js that allows setting up middleware functions to handle requests and responses. Middleware functions have access to the request, response and next objects and can send responses directly without needing to call controllers.

Uploaded by

Vannila
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
  • Introduction to Node.js
  • Modules Overview
  • Advanced Concepts

Node JS

What is NodeJS?
 NodeJS is an environment to run JavaScript outside the browser
 It was created using Chrome V8 JavaScript engine
 It was created by Ryan Dahl, who took chrome V8 engine and built NodeJS on
top of it.

Note:
There is no window(js) object in nodeJS

Globals in Node(like window object in js)


there are global variables we can use. they are
__dirname - path to current directory
__filename – name of the current file
require – used to import modules (es6 in js) but node uses CommonJS library under
the hood to import modules into your js file
process – info about env where your project is executed.
module – module is an global object in nodeJS which has current directory path, file
path and what are the files you have exported and much more. [Link] to see
more.

NodeJS has built-in node modules(packages) that we can use out of the box without
installing them.
there are many modules in node some of them are given below.

OS module:
it has lot of useful methods and properties to know about user’s pc details and much
more
path module:
it is used to create a path for a specific file or directory because not all computers use
same path model. For example
in windows: path is denoted in documents\projects\ (in backward slash)
in mac : path is denoted in forward slash documents/projects/

so we can use this path module to make node automatically create path according to
the user’s pc.

fs module
file system module is used to access file, create , edit, modify a file

To read a file (Synchronous)


const {readFileSync} = require(“fs”)

const readFile = readFileSync(“./content/[Link]”, “utf8”)

path to the file encoding

To create a file and write a file(Synchronous)

const {writeFileSync} = require(“fs”)

const writeFile = writeFileSync(“./content/[Link]”, “Hey, I am a user”)

path where to create content of that file


a file
To append content on a created file
const appendFile = writeFileSync(“./content/[Link]”, “Hey, I am a user”, {flag: “a”})

path where to create content of that file used to


a file. append.

To read and write a file (Asynchronous):

const { readFile, writeFile } = require("fs");

const file = readFile("./[Link]", "utf8", (err, result) => {
    if (err) {
        [Link](err);
    }
    const name = result;
    writeFile("./[Link]", `hey there ${name}`, (err, result) => {
        if (err) {
            [Link](err);
        }
    });
});

This is not the right asynchronous approach because it has a callback hell. The better
approach will be given later.

To continuously run nodeJS we use package called nodemon

npm i nodemon

After installing it go to [Link]


change the following

“script” : {
“dev” : “nodemon [Link]”
}

or

“script” : {
“start” : “nodemon [Link]”
}

Small info about dependency versioning

if a dependency looks like

dependencies: {
“bootstrap” : “^6.2.5”
}
or
dependencies: {
“bootstrap” : “~6.2.5”
}

^ means the dependency can be upgraded >=6.2.5 <7.0.0


~ means the dependency can be upgraded >=6.2.5 <6.3.0

Versioning 6.2.5
6 is major upgrade which means functionality will broke(may) when you update the
older project to a major version of a package

2 is minor upgrade which is backward compatible your project won’t break.

5 is just a patch or bug fix nothing much.

Event Driven Programming


Like in JavaScript we listen for an event (click event or hover event) and respond to
that event.
Same Node JS also event driven programming where we listen for an event and
emit(release or discharge) the response for that event

the way event works in node is We listen for an event and send our response to that
event
in the above example we are importing the events module which is built-in node
package, since it is a class we are creating a instance of a class.
then on is used to listen for an event. response is the event you are listening for .
followed by a callback function to respond to that event.

for all the events we have to emit that event. you will see more details about events
later

Note:
you should always emit the event or else it wont work

Streams in Node JS
Streams is used to read/write file in chunks. If a file is very big in size, you want to
read that file the browser will take more load time to read that file. So what stream
will do is it will send the data in chunks. if a text file is 1MB it will send the data in
chunks i.e 500kb , 500kb

Express JS

Middleware:
Middleware is a function in express. when a user sents a request
req -> MiddlewareFunction -> res (controller)

This middleware function has access to res, res, next object. This is very powerful
because We can directly send a response without the need to contact the controller
if a user sents a request.
Eg:
you can setup a middleware to check if a user is logged in or not when a request
comes from the frontend with the middleware function. If the user logged in then
you can go ahead to call the controllers, if the user has not logged in you can send a
response in the middleware itself.
Note:
You should always invoke the next function in the middleware if you are not sending
any response. the next function is used to call the controller if you don’t invoke it you
get an error. But if you are sending a response in the middleware no need to invoke
the next function.

you can use multiple middleware functions for a single/any route, just add those
functions in an array and all those middleware functions have access to req, res, next
There are two ways to do so
using [Link]
[Link](‘/api/v1/products’, [logger, authorize])

or

[Link](‘/’, [logger, authorize], )

Note:
These middleware functions in the array execute in order keep that in mind

There are three way you can create or get a middleware


1. Express middlewares (eg: [Link]())
2. your own middleware
3. third party library middlewares.

[Link]()
It is used to listen for request from the application for every request. Put the
middleware functions in [Link], serve static files whatever you do it will execute for
every single request if a path is not defined.
Eg:
[Link]([Link]())

so what is now doing is,


When a user sents a request, for every request express middleware checks for any
data which is being sent from the application.

you can specify a path to listen for request also

[Link](‘/products’, logger)

Now [Link] only listens to the route mentioned here and also listens the child route
of /products too. (i.e) products/items

Note:
[Link]() always execute in order only make sure that you always always put
[Link]() in top of all file and make sure the middlewares are executed in [Link]
are in correct order.

Common questions

Powered by AI

Versioning in Node.js, governed by semantic versioning principles, significantly impacts software maintenance and upgrade decisions. Developers need to consider the implications of major, minor, and patch version changes. Major versions may introduce breaking changes that necessitate modifying existing code, while minor versions add new features but remain backward compatible. Patch versions address bug fixes without affecting functionality. Before upgrading dependencies, developers should evaluate whether their code can accommodate potential changes in new versions and conduct thorough testing to ensure compatibility and stability in the updated environment .

In Node.js, dependency versioning uses symbols like caret (^) and tilde (~) to indicate the range of acceptable versions for a package. The caret (^) allows for upgrades to any subsequent minor or patch version within the same major version, ensuring compatibility (e.g., ^6.2.5 implies versions >=6.2.5 <7.0.0). The tilde (~) limits upgrades to subsequent patch versions within the same minor version (e.g., ~6.2.5 means >=6.2.5 <6.3.0). A major version change (first digit) may involve breaking changes, a minor version (second digit) introduces new backward-compatible features, and patch (third digit) covers bug fixes .

In Express.js, middleware functions are used to process requests and can manipulate request and response objects, manage user authentication, and execute any code necessary before passing control to the next middleware function. For managing user authentication, a middleware function can check if a user is logged in by verifying credentials or session tokens. If authentication is successful, the middleware can invoke the 'next' function to pass control to the subsequent handlers; otherwise, it can send a response directly without proceeding further. This layered architecture enhances modularity and security by centralizing authentication logic .

Node.js enables JavaScript execution outside the browser by providing an environment built on the Chrome V8 JavaScript engine, which is capable of interpreting and running JavaScript directly. Ryan Dahl took the V8 engine, designed for Google's Chrome browser, and developed Node.js to allow server-side scripting applications. Unlike in browsers, Node.js lacks the window object; instead, it uses global objects like __dirname and __filename to provide environment-specific functionalities .

Synchronous file operations in Node.js involve methods like readFileSync and writeFileSync from the 'fs' module, which block the execution until the operation is complete, potentially leading to poor performance in real-time applications. Asynchronous operations, however, utilize methods like readFile and writeFile, which allow for non-blocking execution and better performance by using callbacks or promises to handle operation completion. Asynchronous I/O prevents the blocking of the main execution thread, enhancing application efficiency, especially when dealing with large files or data streams .

Streams in Node.js enhance application performance by allowing data to be read or written in chunks rather than loading entire files into memory at once. This method is particularly advantageous when dealing with large files, as it reduces memory consumption and allows large amounts of data to be processed incrementally. For instance, rather than loading a 1MB file all at once, streams might split it into multiple smaller parts (e.g., 500KB chunks), thus minimizing load time and the risk of application slowdown or crashes due to memory overload .

The nodemon package is used to automatically restart a Node.js application when file changes in the directory are detected. This enhances the development workflow by allowing developers to see changes in the application without manually stopping and restarting the server. By updating the script in package.json to include a command like "nodemon app.js", developers can streamline their development process, reducing downtime and improving efficiency .

In Express.js, multiple middleware functions can be managed by passing them as an array to routes using app.use() or route handlers like app.get(). These middleware functions will execute sequentially in the order they are listed, which is crucial for operations that depend on previous middleware actions (e.g., logging before authentication). Developers must ensure the order aligns with the application's logical flow—middleware for logging, parsing, and authentication should be arranged appropriately to avoid errors and ensure each function performs its task without interference .

Node.js implements event-driven programming by utilizing an events module which allows for asynchronous handling of events. In this paradigm, the 'on' method is used to listen for specific events, and the 'emit' function triggers the specified event, executing any associated callback functions. This model is significant because it allows Node.js applications to handle multiple I/O operations efficiently without blocking the execution thread, promoting high performance and scalability .

The app.use() function in Express.js is pivotal for applying middleware across all requests or specific routes. It sets middleware that can intercept request processing, implementing cross-cutting concerns like security, logging, or data parsing. Middleware defined with app.use() is executed in a top-down order and affects subsequent parts of the routing tree. This hierarchical execution order necessitates that developers place app.use() calls sensibly to ensure middleware is applied at the correct processing stage, optimizing request handling efficiency and behavioral consistency across application layers .

Node JS
What is NodeJS?

NodeJS is an environment to run JavaScript outside the browser

It was created using Chrome V8 Jav
path module:
it is used to create a path for a specific file or directory because not all computers use
same path model. For
To append content on a created file 
const appendFile = writeFileSync(“./content/users.txt”, “Hey, I am a user”, {flag: “a”})
“dev” : “nodemon app.js”
}
or
“script” : {
“start” : “nodemon app.js”
}
Small info about dependency versioning
if a dependenc
6  is major upgrade which means functionality will broke(may) when you update the 
older project to a major version of a pack
in the above example we are importing the events module which is built-in node 
package, since it is a class we are creating
you can setup a middleware to check if a user is logged in or not when a request 
comes from the frontend with the middleware
It is used to listen for request from the application for every request. Put the 
middleware functions in app.use, serve stat

You might also like