Introduction to Node.js, v3

Creating a Basic Server

Scott Moss

Scott Moss

Superfilter AI
Introduction to Node.js, v3

Check out a free preview of the full Introduction to Node.js, v3 course

The "Creating a Basic Server" Lesson is part of the full, Introduction to Node.js, v3 course featured in this preview video. Here's what you'd learn in this lesson:

Scott discusses the concept of a Node.js server, which listens for incoming network requests and responds by executing code or providing data. A walk through the process of creating a basic Node.js server is also covered this segment.

Preview
Close

Transcript from the "Creating a Basic Server" Lesson

[00:00:00]
>> Hopefully, I didn't traumatize you with testing. I was only trying to prepare you for what is to come with testing, but it can be fun. Like I said, go check out some of those courses. I'm sure smarter people than me have better ways to do testing that are enjoyable.

[00:00:13]
So go check those out and let me know on Twitter what you think. And help me with my testing, so thank you. Now we will move on to servers. So we built the CLI, we've talked about file systems, we've done asynchronous programming. I mean at this point we've done it all.

[00:00:32]
If you just stopped right there and combined all that, you could build so many things in Node. I'm just gonna list some things you've used before, that use just those things. So, Webpack, Parcel, Vite, any build tool uses everything, you just learn. It's a CLI with file systems.

[00:00:51]
That's literally all they do, right? I mean, [LAUGH] they do way more than that, but at the end of the day, that's the core of those apps. Any tool that scaffolds out files for you, a linting tool, you're using a tool that lints things. It's a CLI that reads files and does things.

[00:01:12]
Actually a lot of those linters depending on how you run them might have servers as well, but most of the time it's like a reading a file. I'm applying regexes and rules to it, and I'm giving you some output from that right at the end of the day so a lot of stuff.

[00:01:27]
But now we're gonna talk about servers, which is probably the most popular and obvious thing for any OS level language, and Node.js is no different. So in the context of Node, a server is really just a program that listens for incoming network request and that that's really it, and then it just returns a response to that network request.

[00:01:47]
So what is a network request? I mean, if I go here and hit refresh, I just did a network request, right? So if I go to the console, I go click on network, I can see the requests that I made. So I'm going to click on All, refresh this.

[00:02:04]
And all the network requests that were made on this page are, this is so big, there we go. It's a lot probably for this page, but 59 requests, but as you can see, each one of these is a network request. It went somewhere to the Internet, and it came back with something.

[00:02:20]
Let's just look at the HTML ones. So if we click on doc, we can see back. We can see we got the HTML for this website right here. Here's the raw HTML, or in this case, it looks like it's not writing HTML. This is using some JavaScript. But as you can see, it's just going over Internet, and it's getting some information back, but from where?

[00:02:44]
Where is this information coming from? That's a server. It's going to a server. Each one of these addresses, as you can see when I hover over this, it has an address. That's a location to a server somewhere, right? And that server can respond back with anything. In this case, it respond back with some HTML.

[00:03:01]
And there's different types of servers. There's traditional servers that run constantly. There's CDNs, which are basically servers that are replicated across the world and are directed, has traffic directed to them based off geographical location, and they can cache things. There's serverless servers, servers that aren't on until you actually make a request to them, then they turn on, then they turn off.

[00:03:27]
There's so many different types of servers. At the end of the day, it's just a computer that's connected to the internet that can handle requests. And it can handle requests by sending back all different types and forms of data. So we're talking JSON. We're talking HTML images, CSS JavaScript files, streaming data, audio, video, email, anything that's data it can send back.

[00:03:50]
So that's basically what a server is. Some servers are real time as they have two-way communication. Have you ever played a video game or if you've done a Google doc You can see the presence of someone being on that document? That's real time. Some servers are not real time like HTTP, and you can only make a request and get a response.

[00:04:11]
But you can do all of that plus more in Node.js. So it can get pretty complicated. But for us, we're going to talk about A Simple HTTP Server, that just sends back some content. So by default, we get to use the core embedded, or I'm sorry, core internal node module called HTTP, and we can do that to create a server.

[00:04:36]
So let's give it a try. So I'm gonna walk through that, and then we'll test it out. So I'm just gonna make a new file here called server. It's mostly just test code here. So I'm gonna import http from node http, and basically to create a server with this, all we have to do is just use this create server function, right?

[00:04:59]
So we can say server equals create or http.createServer, takes a callback because it's asynchronous, and we get two things back here. The first one is always gonna be the incoming request objects, and the second one is always gonna be an object in which we can use to respond to the request.

[00:05:21]
That's a pattern you'll see all the time req response, req res, req res, that's the request, that's the response. This is who's asking, this is how we reply. Okay, and then from there, there's a bunch of different things. We can do status code, so we can set the status code.

[00:05:40]
So I can say status code is 200. There's a whole thing about status codes, but at the end of the day, it's actually quite simple. And really, they're they're mostly for browsers and people who respect this. But status codes are just a way for us, as it's just a way for applications to notify other applications what the status of a request was, right?

[00:06:02]
Because the applications aren't gonna read the data to understand what the status was, but a status code is helpful. So if you anything that's between 200 to 300 is successful, anything in the 300 is successful, but cached. This data isn't fresh. It was cached by the browser or the server.

[00:06:22]
Anything in the four hundreds is the user sent a bad request. Anything in the five hundreds is the server messed up? That's basically it. So 200, 300, good, 400 user messed up 500, server messed up. And there's different status codes for instance, you know a 401 means you sent the wrong information a 404, which you've probably seen before, it means this URL does not exist, right?

[00:06:53]
A 500 might mean our server died. Sorry. Alright, a 503 might be your not your forbidden or sorry, that's 403 or 503. I don't know what that is. It might be like a payment thing. That's a 502. I don't know. There's a lot of them. You just don't remember these things.

[00:07:08]
You just go look them up. You just go reference them. So that's status codes. And some technologies don't even care about status codes, like GraphQL literally does not care about status codes, everything's a 200. It doesn't matter. It literally uses the data to determine what the status of something was and not the codes themselves.

[00:07:25]
Status codes these days are mostly for other systems like browsers, cuz a chrome or any browser knows what to do and what to show. If a certain status code comes in, If it sees like a 400, it'll show a red error your console because it sees a 400.

[00:07:39]
If it sees a 200, it won't show that I don't think it was successful, even though you might have sent back an error. So it's mostly for other systems. So I got status code. We can set things like a header. So in this case I can say res.setHeader and a headers are just basically like a collection of key value pairs.

[00:07:57]
So one of the most popular useful headers is content type. This is gonna determine what type of, this is telling the client what type of data you're sending back to it. So in this case, you use a specific MIME type. If you don't know what a MIME type is, a Mime type is basically like the equivalent of a file type, but for the Internet.

[00:08:19]
It's like, this is the type of data that I'm going to send you right in this example I'm using, is a type of text that is plain, and there's all different types of MIMEs out there, right? I might be able to do like, data JSON or something like that, right?

[00:08:42]
This is one of the things you also just got to look up cuz there are so many of them, or I could be like text HTML or something like that. There's images, there's so many things. In this case, I'm just ponna send back plain text. This is just so the browser knows how to process this.

[00:08:57]
If you really think about it, a browser is an app that can render all different sorts of content. You give it a PDF, it'll show it. You give it an HTML file, it'll show it. You give it JavaScript, it'll execute it. It can render so many different types of files.

[00:09:09]
This is how you help it understand what that file is, with just this one header. Okay, and then now the last thing we can do is we can just end, as in okay, we're done. We're responding back to the client. We can say res.end, and send back a message, Hello there, right?

[00:09:27]
Cool, so now we got that, the next thing we need to do is we need to start the server. So we can say server.listen, and servers listen on ports. So what is a port? A port you have to have, you have to connect to a port. You have to use a port in order to connect to a socket which enables us to do HTTP communication.

[00:09:51]
If your computer's a server, it's just not connected to the World Wide Web, but it has ports on it. So you have to have your server listen on a port. It's just a four-digit number, sometimes a five-digit number, very common ones you might see are like 3000, 3001, 4000, 5000.

[00:10:09]
Just pick a four digit number. It's not special. Just pick one. You have to think too hard about it. When you're actually working on an app at your job, you'll probably have 10 of these running at any given time with all different ports. You might get an error saying, this port's already in use and you can't use it.

[00:10:23]
Pick another number, add a one to it, and try again. There's also tools to help you that you can download up here in your toolbar that might show you what ports are being used, or you could use a terminal for that as well. I'm just gonna listen on 4000.

[00:10:38]
You can pick whatever number you want. Always I'm picking 4000. Think I have something on 3000 right now. I think I have something of 5000, I don't know. We're gonna figure out I always got something running on my machine. So this is also asynchronous. So when this is done, I was going to say console dot log.

[00:10:54]
Server running on port 4000 like that. I'm just gonna do that. Actually, I'm just gonna put the whole URL here so I can click on it in my terminal. So localhost 4000, http goes 4000. So it's always gonna be localhost. Or it'll be, you know, the localhost IP, which we want to 127.0.0.1, but you could just put localhost.

[00:11:27]
Cool, and then the port is after the colon. So even websites have ports, right? This website has a port. It's just that it's dropped. You don't see it, but every deployed website is on like Port 80. Every website, you just don't see it, but it's like there. So we're on port 4000 on our local host not deployed to the Internet.

[00:11:44]
So we have our server, and now we can just run this, right? So we can say node server.js and boom. Two things to note here, the program didn't stop. It's still running. Every up until now, we'd run the program and then it would stop. It would shut down.

[00:12:03]
We run the command, and then it would stop. I ran the command and it's still running. I can exit it. See, I had to exit it to quit it. So servers are always on. They're like listening, that's why you need a port. So they're waiting for an incoming request.

[00:12:17]
So that's why you hear like, my God, someone's server crashed. Yeah, it did this, it did they die. So now I can't handle requests. It's a bad thing. If your servers crashed, unless you have something like serverless where it's never on, it's just, it only spins up when you need it.

[00:12:33]
But for the most part, you don't want your service crashing. So that's one thing. Now, if I go to this, this thing just freaks out. Why did it freak out? Status code is not a function maybe it's just data's no it's not a function, it's a property. There we go, try that again.

[00:13:00]
And refresh, and then there we go, hello there. I get back hello there from my server.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now