Node.js Ultimate Beginner’s Guide in 7 Easy Steps

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
one of the most valuable skills to have as a full stack web developer is without a doubt no js' and that's not going to change anytime soon but you might be wondering why I'm making a note tutorial in 2020 because if you've been watching the news you may have heard that note was killed last week by denno making the extremely chaotic JavaScript world even more convoluted if you're just starting to learn JavaScript this can be very confusing and you might be wondering should I learn node or denno the answer is node especially if you want to get a job or build a product when something becomes as established as node it doesn't get replaced you'll see things like this happen all the time a few years ago everybody was saying graph QL would replace rest and ten years ago people were saying no js' would replace PHP these predictions never pan out and are just built on top of hype that being said I do think denno is awesome and has a bright future both both but both is good and if you learn no today those skills will mostly transfer to denno tomorrow in today's video you'll learn the basics of nodejs in seven easy steps then we'll put those steps together to build a full stack web application because in my opinion the best way to learn how to code is to build something meaningful from scratch by the end of the video we'll deploy our code to the cloud so you can show off your API to your friends and family if you're new here like and subscribe and head over to fire ship IO to follow along with the full write-up to this video step one is to understand what nodejs is and why you would want to use it no 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 nodejs 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 no 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 but if you really want to dive into how nodejs works check out my how it's made video but what kind of problems can no js' actually solve no js' can do a lot so instead of listing out a bunch of use cases i'll show you how to build a full stack web application from scratch this how it'll work you visit a URL on the internet that points to your server when the request is received we can use node to handle the requests and read a file from the server's filesystem and then respond back to the client so they can view the HTML in the browser step 2 how to install nodejs node can be installed on Windows Mac or Linux and is probably already installed on your system in this tutorial I'll be using ubuntu via the windows subsystem for Linux at this point I've just opened up in empty directory in vs code and then pulled up a terminal session you can find out if note is installed on your system by running node flag V from the command line as you can see here I'm running version 12.16 which is the current long-term support version if you get an error at this point it means that you don't have node installed and even if you do have node installed 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 for Windows go ahead and follow the instructions to install NPM on your system and that will give you the ability to install any version of nodejs that you want for example you could run npm install 12.16 dot 3 then run NPM use to use that specific version as your runtime and now that we have no js' installed we can move on to step 3 HelloWorld but first if you're serious about nodejs consider becoming a pro member at fire ship io it'll give you access to my full-length courses almost all of which cover advanced use cases for nodejs but we need to walk before we can run so how do we actually use this thing one way to mess around with node is in rappel mode which stands for read eval print loop when you type node into the command line it allows you to run JavaScript code and will 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 but go ahead and hit ctrl C twice to shut it down because in most cases we'll want to execute JavaScript code that lives in an actual file the default entry point into a node.js app is the index.js file and go ahead and create an index J s file manually in the vs code then inside that file at console log hello world you can now run the code inside this file with the node command followed by the path to this file and because it's an index file you can actually just point to the parent directory congratulations you just built a node out step four understand the node runtime in most ways JavaScript works the same way it does and the browser as it does in ojs but there are some very important differences you should know about first node has a handful of built-in identifiers x' one of those Global's is console which we've already been using to log out values to the terminal there is a another global with a 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 front-end web developer you can compare global to the window object in the browser now I think the most important global to be familiar with is 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 but this gives us a great opportunity to segue into step 5 how do events work in nodejs 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 no js' very suitable for things that require high throughput like real time applications web servers and things like that ok 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 events can come in many forms but 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 no js' will run this function and that's where it gets the name callback because the function isn't called the first time nodejs sees it it's only called after the exit event occurs at some point in the future this event is built-in de node but you can also create your own from scratch well 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 ready 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 and with that we can move on to step 6 the file system note 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 allow me to explain that by showing you an example first create a file on the file system called hello dot txt and then add whatever text you want inside of it in our JavaScript code we'll import to functions from the file system module called read file and read file sync 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 a 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 luckily you can make your code non-blocking by refactoring this to a callback with read file we passed 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 logs 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 but there's actually 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 read file from the promises namespace this gives us a function that returns a promise when called if you're using the latest bleeding-edge version of node you could potentially use this function with top-level await which means you can use a wait to resolve the promise here at the top of the script however since we're currently using node version 12 we'll go ahead and wrap this in an async function and this async/await syntax will make your code much easier to read especially when you have molt pull async calls in the same function okay so now that you know how to read files I want to backtrack a little bit and talk about this require function that you've seen me use in the past couple examples step seven modules a module is nothing more than a JavaScript file that exports its code note has a bunch of built-in modules like FS and events that we've already looked at and there's a long list of other modules beyond that the traditional way to import a module a node is to use this require function but a quick sidenote on that first because node recently added support for es modules which use the import-export syntax most node.js code out there written and vanilla JavaScript still uses require so it's very important for you to know as a nodejs developer and if all that's confusing to you well all I can say is welcome to the JavaScript world let's look at how we can use modules in our own code base create a new file to serve as your module then go into your index.js file create a variable for the module and then import it using require when you console.log it you'll notice that it's currently just an empty object in order to make a module useful you need to export some code from it in the modules file you can reference this object with module exports you can add new properties to the object or redefine it as a new object in either case whatever you add here will now be available to use in the other file and as you can see the object is no longer empty when we console.log it but at some point you'll very likely want to use somebody else's code out there in the world and the primary place to do that is via node package manager or NPM which was recently acquired by github which itself was recently acquired by Microsoft when you installed node earlier in the video it also installed NPM which is a tool you can use to install remote packages to use in your own code the first step we'll want to take is to open the command line and run NPM and it will use the white flag to use the default options and what you'll notice is that it creates a package.json file here in the root of the application this file can contain metadata about your project but most importantly it keeps track of the dependencies that you use here at this point we haven't installed anything yet so let's go ahead and change that by opening the command line again and running NPM install Express Express is a minimal web application framework and one of the most popular third-party node modules after running the command you'll notice a few things happened here in the package.json file it added Express to the dependencies and pegged to a specific version this Dependencies object allows you to manage multiple dependencies in a project and then reinstall them all at once on a different system now the actual raw source code for the dependency lives in this node modules directory you should never have to modify code in the node modules directory if you find yourself writing code in here you're probably doing it wrong that's because the package.json controls how this directory is built it fetches your remote packages saves the source code here and that process should be able to be repeated on any system now that we have this package installed we can import it by name in our JavaScript code in this case we simply require Express and now we've reached the point where we're ready to put these seven steps together to build a real full-stack application and deploy it to the cloud what we're building here is actually just your typical full stack web application our server will live on a URL and when a user makes a request to this URL in the browser the server will respond with some HTML in our code will first create an instance of an express app an express app allows us to create different URLs and endpoints that a user can navigate to in the browser and then we defined code for the server to handle those requests now I don't want to get too deep into HTTP but when the user navigates to a URL in the browser it's what's known as a get request which means they're requesting some data on the server and not trying to modify or update anything on the server with express we can set up an endpoint like that by calling apt-get and in the first argument is the URL that the user will navigate to in this case we'll just use a forward slash for the route URL but feel free to create multiple pages for your web app by creating different URLs the second argument here is our callback function you can think of every request to this URL as an event and then you handle that event with this function and Express gives us two parameters to make use of the request and the response the request is the incoming data from the user in this example we don't really need to parse any data from the request however in many cases you might want to look at the headers or the body of the request to authenticate a user or understand what the user is trying to do at this point we need to implement the code to handle the request what we want to do is read some HTML from our file system and then send it back down to the browser as you can see here I'm creating a file called home HTML with just some generic HTML markup inside in our source code we can then import read file from notes system module just like we did earlier we'll read the file use utf-8 encoding then in our callback function here we'll have access to the HTML string and we can send a response back down to the client by calling response dot send and also if there's an error in the callback we can handle that by sending a response with a status code of five hundred which means a server error so the user knows that something went wrong on the server and that's all there is to it we now have a way to send HTML from the server to the client now 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 dot listen with that port and when it starts up we'll console.log that the app is available on localhost 3000 you can start it up by opening the command line and run a node with the current working directory if you go ahead and open it in the browser you should see your HTML return back to you now there is one important thing you should know at this point and that's that callbacks can be very difficult to work with especially as your app grows in complexity it often leads to a state known as callback hell 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 and no js' instead of importing read file from FS we'll import it from FS dot 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 so now that we've built a node.js app how do we deploy it to the cloud so people can actually use it there's a bunch of different ways we could do it but an easy and free way is with Google App Engine App Engine has what's known as a standard environment for nodejs up to version 12 and what that does is provide you with a server in the cloud that scales automatically based on the incoming traffic to your app it's incredibly easy to set up but you first need to have a Google cloud platform account and also the Google Cloud command line tools installed on your local system once you have that done you can simply go into your source code and create an app gamma file this file is used to configure your cloud server the only thing we need at this point is to specify a runtime no js' version 12 App Engine will run your code by looking in the package.json file for a start script so let's go in there and define a start script that runs node in the current working directory to start our Express app from there we can simply open the command line and run g-cloud app deploy that'll take a minute and then it will give you a URL where you can access your app publicly on the web congratulations you're now a full-stack cloud architect if this video helped you please like and subscribe and if you really want to dive deep into nodejs and express consider becoming a pro member at fire ship IO I have a whole bunch of advanced content cover in real-world use cases with these technologies thanks for watching and I will see you in the next one [Music]
Info
Channel: Fireship
Views: 581,070
Rating: 4.95994 out of 5
Keywords: webdev, app development, lesson, tutorial, node, deno, node.js, nodejs basics, nodejs tutorial, php, fullstack web, http, gcp
Id: ENrzD9HAZK4
Channel Id: undefined
Length: 16min 20sec (980 seconds)
Published: Thu May 21 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.