Node Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

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. console.log 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/names.txt”, “utf8”)

path to the file encoding

To create a file and write a file(Synchronous)

const {writeFileSync} = require(“fs”)

const writeFile = writeFileSync(“./content/users.txt”, “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/users.txt”, “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("./users.txt", "utf8", (err, result) => {
    if (err) {
        console.log(err);
    }
    const name = result;
    writeFile("./hello.txt", `hey there ${name}`, (err, result) => {
        if (err) {
            console.log(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 package.json


change the following

“script” : {
“dev” : “nodemon app.js”
}

or

“script” : {
“start” : “nodemon app.js”
}

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 app.use
app.use(‘/api/v1/products’, [logger, authorize])

or

app.get(‘/’, [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: express.static())
2. your own middleware
3. third party library middlewares.

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

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

app.use(‘/products’, logger)

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

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

You might also like