0% found this document useful (0 votes)
6 views

Node Js

Node.js is a runtime that enables JavaScript to be executed on the server side, revolutionizing web development by allowing full-stack applications to be built in a single language. It operates on an asynchronous, event-driven model, making it suitable for high-throughput applications like web servers. The document also covers installation, usage of built-in modules, handling of asynchronous operations, and the role of middleware in application development.
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)
6 views

Node Js

Node.js is a runtime that enables JavaScript to be executed on the server side, revolutionizing web development by allowing full-stack applications to be built in a single language. It operates on an asynchronous, event-driven model, making it suitable for high-throughput applications like web servers. The document also covers installation, usage of built-in modules, handling of asynchronous operations, and the role of middleware in application development.
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
You are on page 1/ 20

What is Node.JS?

Runtime

● Node.js itself is not a programming language but rather a runtime that allows you to run
javascript on a server you see when javascript first came around in the 1990s it was
designed as a simple scripting language to run in the browser as the web platform
evolved javascript became more and more powerful.

● And in 2009 we saw the initial release of node.js. Now up until this time it was impossible
to write javascript code on the server most servers were written in languages like java or
php. It revolutionized web development because now a web developer could write a full
stack application in a single language.

● So that's all node.js is it's a way for developers to write javascript on the server
when it could previously only be written in a web browser now there are a lot of low-
level implementation details here that you don't need to know about as a beginner.

Figure 1.0 - 2013 Poll Most Backend Programming Language Used


● You visit a url on the internet that points to your server when the request is received. We
can use node to handle the request and read a file from the server's file system and then
respond back to the client so they can view the html in the browser.

Installing Node

● It'd be a very good idea to use a package called node version manager to manage the
installation of different node versions on your system. There's an nvm package for mac
and linux or a separate package.

Figure 1.0 - Node Version Manager (NVM)

Figure 1.1 - NVM Install


Console Log (Hello World)

● One way to mess around with node is in REPL mode which stands for read, evaluate,
print, loop when you type node into the command line it allows you to run javascript code
and we'll print out the results for example we can type console.log hello world and it will
log that value out this is nice for messing around.

● REPL stands for Read Evaluate Print Loop, and it is a programming language
environment (basically a console window) that takes a single expression as user input
and returns the result back to the console after execution. The REPL session provides a
convenient way to quickly test simple JavaScript code.

Figure 1.0 - Hello World


Know your Runtime

● Node has a handful of built-in identifiers one of those globals is console which we've
already been using to log out values to the terminal

● There's another global with the name of global. This object is a namespace that is
available throughout the entire node process for example if we assigned a lucky number
property to global we could then access it anywhere else in our code if you're a frontend
web developer you can compare global to the window object.

● The most important global to be familiar with is the process which gives you access to
the currently running node process. You might use it to check the current platform or
operating system which in my case is linux or grab an environment variable from your
server.

Figure 1.0 - Global Object


Figure 1.1 - Process Object 1

Figure 1.2 - Process Object 2

Events
Figure 1.0 - Node.js

● In node.js you'll often hear people describe it as an asynchronous event-driven javascript


runtime.

● The runtime implements a thing called an event loop just like a web browser does and it
allows Node to push intensive operations off to a separate thread so only very fast non-
blocking operations happen on the main thread and this is why people often call node
non-blocking.

● It's a design choice that makes node.js very suitable for things that require high
throughput like real-time applications web servers and things like that okay so how does
that affect me as a coder well normally you won't have to think about the low-level details
you just need to know how events and callbacks work in most cases you'll listen to
events.
Figure 1.1 - Node.js System Diagram

Figure 1.2 - Callback Function in Node JS

● One example is on the process global that we looked at earlier before a node process
finishes it emits an event named exit we can listen to this event using on and then
register a callback function as the second argument when the exit event occurs
Node.js will run this function and that's where it gets the name callback because the
function isn't called the first time Node.js sees it it's only called after the exit event
occurs.
● At some point in the future this event is built into node but you can also create your own
from scratch we'll import an Event Emitter from the events module that is built into node
and we'll look at modules in more detail in just a minute we can create a custom event
emitter by instantiating the class and then we'll register a callback that fires on the lunch
event now that the callback is registered you can simply call event emitter emit with that
event name and that triggers your callback function to run as you can see here we emit
the event twice which will run the callback function twice this event driven style of
programming is extremely useful when you have something that is cpu intensive.

Figure 1.3 - Event Emitter

Figure 1.4 - Event Emitter Console Log


File System

Figure 1.4 - File System Module

Figure 1.5 - readFileSync Function

● The file system node has a built-in file system module called fs. It can read, write, and
delete files on the file system among other things and it can also do things in a blocking
or non-blocking way.

● We'll import two functions from the file system module called readFile and
readFileSync. Anytime you see a function that ends in Sync think blocking or in
other words it will need to finish all of its work before any of your other code can
run we can read a text file in node by simply passing the path to that file and then we'll
specify the encoding as utf-8 now reading a file might take a while especially if it's a very
large file and what you'll notice here when we run our code is that the second console
log won't run until after that file has been read.
Figure 1.6 - ReadFileSync Function

Figure 1.7 - ReadFile Function with Callback Function

● You can make your code non-blocking by refactoring this to a callback with readfile
we pass the same first two arguments and then add a callback function as the third
argument inside the function we can access an error object if the operation fails or when
successful the actual text from the file the super cool thing about this is that even though
the console log to the text file comes first in our script it's not the thing that gets executed
first node registers the callback executes the rest of the script and then finally runs the
callback when the file has been read so that gives us two different ways to read a file.
Figure 1.8 - Async Function and Promise

● One other way we could go about this and that's using a promise-based solution.
Promises are also asynchronous and non-blocking and they tend to produce much
cleaner code when compared to callbacks. Notice how in this example we're importing
readfile from the promises namespace this gives us a function that returns a promise
when called.

A. JS Promises (Async Await)

Figure 1.0 - Await

● https://www.youtube.com/watch?v=li7FzDHYZpc

● Await does exactly what it says it allows us to wait until the promise has completed
before moving on to the next line this makes our code a lot neater and easier to read.
Javascript requires our await keywords be used inside functions marked with the async
keyword.
Figure 1.1 - Async Await

Modules and NPM

Figure 1.0 - Common JS Syntax v.s. ES Modules Syntax


Figure 1.1 - Require Function

Figure 1.2 - Module.exports


● Express app allows us to create different urls and endpoints that a user can navigate to
in the browser and then we define code for the server to handle those requests.

Figure 1.3 - Create Instance of Express

Figure 1.4 - Get Request Method

● Request - user’s incoming data.


● Response - your outgoing data.
Figure 1.5 - ReadFile Function inside Get Request Method

● A callback hell is where you have a bunch of callbacks nested within callbacks within
more callbacks and so on.

● A great way to avoid code like this is to use promises instead of callbacks and that's very
easy to do in node.js instead of importing read file from fs we'll import it from fs.promises
we can make our callback function async and then we can write the response in a single
line of code by saying response send and then await the operation to read file that's
much more concise and readable but it's especially useful when you have multiple async
operations to handle in a single request.

Figure 1.6 - App.Listen()

● We just need to tell our express app to start listening to incoming requests. We do that
by defining a port which will normally come from a node environment variable then we
call app.listen with that port and when it starts up we'll console.log that the app is
available on localhost 3000.
Middleware
● Middleware is software and cloud services that provide common services and
capabilities to applications and help developers and operators build and deploy
applications more efficiently. Middleware acts like the connective tissue between
applications, data, and users.

● Middleware has been part of software engineering terminology since the late 1960s, and
as a category can apply to a wide range of modern software components. Middleware
can include application runtimes, enterprise application integration and various kinds of
cloud services. Data management, application services, messaging, authentication, and
application programming interface (API) management are all commonly handled by
middleware.

● Today middleware is the technological foundation for modern cloud-native architectures.


For organizations with multi-cloud and containerized environments, middleware can
make it cost-effective to develop and run applications at scale.
Figure 1.0 - Middleware with App.Use()

● Volleyball apt use is used for middleware meaning we have some function that's
going to operate on incoming requests. Volleyball is a middleware because every
single incoming request it logs to the console like we can see those logs here and
it's actually let's like watch it so any request that comes in to our server volleyball is
taking care of logging that out and it can do that because as a middleware it has access
to every single incoming request and when you do use without a path that means literally
any requests coming in to our app is gonna run through this middleware when you add a
path.

● Middleware it has access to every single incoming request and when you do use without
a path that means literally any requests coming in to our app is gonna run through this
middleware when you add a path we're only saying any requests where the URL
beginning of the URL matches this will actually run through our middlewares.

● And you could think of a router as essentially just a stack of middlewares it's a
bunch of different middlewares and even our app is middleware so like this is a very
specific middleware it only will run when it's a get request and this is the path but it's still
considered a middleware because our request is running through it so this says only
match requests that begin with slash off this says match absolutely any request.

A. What kinds of middleware are there?

Figure 1.1 - New Application Development & Optimization of Existing Applications


Figure 1.2 - Comprehensive Integration & Application Programming Interfaces (APIs)

Figure 1.3 - Data Streaming & Intelligent Business Automation


Figure 1.4 - Body-Parser

● A package called body-parser, it is a middleware that accepts the incoming requests


and will parse the body as JSON so we can actually use it.

Figure 1.5 - Body-Parser.json

Blog Fullstack Lama Dev


Blog Fullstack Lama Dev: https://www.youtube.com/watch?v=0aPLk2e2Z3g&t=6014s

You might also like