Node Js
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.
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.
● 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.
● 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.
Events
Figure 1.0 - Node.js
● 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
● 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.
● 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
● 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.
● 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
● 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.
● 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.
● 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.