(This page has no text content)
N O D E . J S Build Web APIs and Applications with Node.js 4nd edition by John Bach 2021
Memlnc.com INTRODUCTION WHAT IS NODE.JS? HOW DO I INSTALL NODE.JS? NODE BINARIES VS VERSION MANAGER “HELLO, WORLD!” THE NODE.JS WAY NODE HELLO.JS NODE.JS HAS EXCELLENT SUPPORT FOR MODERN JAVASCRIPT INSTALLING A PACKAGE GLOBALLY JSHINT INDEX.JS INSTALLING A PACKAGE LOCALLY JAVASCRIPT AND NODE.JS JAVASCRIPT AND YOU AN ADVERT SERVER SIDE JAVASCRIPT "HELLO WORLD" A COMPLETE WEB APPLICATION WITH NODE.JS
USE CASES THE APPLICATION STACK BUILDING THE APPLICATION STACK A BASIC HTTP SERVER ANALYZING OUR HTTP SERVER PASSING FUNCTIONS FROM SIDE TO SIDE HOW PASSING FUNCTIONS MAKES OUR HTTP SERVER WORK EVENT DRIVEN CALLBACKS HOW OUR SERVER MANIPULATES REQUESTS FINDING A PLACE FOR OUR SERVER MODULE WHAT IS NEEDED TO "ROUTE" REQUESTS? EXECUTION IN THE REALM OF VERBS ROUTING TO TRUE REQUEST HANDLERS MAKING PETITION HANDLERS RESPOND HOW SHOULD THIS NOT BE DONE? BLOCKING AND NON-BLOCKING RESPONDING TO REQUEST HANDLERS WITH NON-BLOCKING OPERATIONS SERVING SOMETHING USEFUL HANDLING POST REQUESTS Introduction
What Is Node.js? There are plenty of definitions to be found online. Let’s take a look at a couple of the more popular ones. This is what the project’s home page has to say: - Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine. And this is what Stack Overflow has to offer: - Node.js is an event-based, non-blocking, asynchronous I/O runtime that uses Google’s V8 JavaScript engine and libuv library. Hmmm, “event-based”, “non-blocking”, “asynchronous I/O” — that’s quite a lot to digest in one go. So let’s approach this from a different angle and begin by focusing on the other detail that both descriptions mention — the V8 JavaScript engine. Node Is Built on Google Chrome’s V8 JavaScript Engine The V8 engine is the open-source JavaScript engine that runs in Google Chrome and other Chromium-based web browsers, including Brave, Opera, and Vivaldi. It was designed with performance in mind and is responsible for compiling JavaScript directly to native machine code that your computer can execute. However, when we say that Node is built on the V8 engine, we don’t mean that Node programs are executed in a browser. They aren’t. Rather, the creator of Node (Ryan Dahl) took the V8 engine and enhanced it with
various features, such as a file system API, an HTTP library, and a number of operating system–related utility methods. This means that Node.js is a program we can use to execute JavaScript on our computers. In other words, it’s a JavaScript runtime. How Do I Install Node.js? In this next section, we’ll install Node and write a couple of simple programs. We’ll also look at npm, a package manager that comes bundled with Node. Node Binaries vs Version Manager Many websites will recommend that you head to the official Node download page and grab the Node binaries for your system. While that works, I would suggest that you use a version manager instead. This is a program that allows you to install multiple versions of Node and switch between them at will. There are various advantages to using a version manager. For example, it negates potential permission issues when using Node with npm and lets you set a Node version on a per-project basis. If you fancy going the version manager route, please consult our quick tip: Install Multiple Versions of Node.js using nvm. Otherwise, grab the correct binaries for your system from the link above and install those. “Hello, World!” the Node.js Way
You can check that Node is installed on your system by opening a terminal and typing node -v. If all has gone well, you should see something like v12.14.1 displayed. This is the current LTS version at the time of writing. Next, create a new file hello.js and copy in the following code: console.log("Hello, World!"); This uses Node’s built-in console module to display a message in a terminal window. To run the example, enter the following command: node hello.js Make the leap into server-side programming with a comprehensive cover of PHP & MySQL. Normally RRP $11.95 Yours absolutely free If Node.js is configured properly, “Hello, World!” will be displayed. Node.js Has Excellent Support for Modern JavaScript As can be seen on this compatibility table, Node has excellent support for ECMAScript 2015 (ES6) and beyond. As you’re only targeting one runtime (a specific version of the V8 engine), this means that you can write your JavaScript using the latest and most modern syntax. It also means that you don’t generally have to worry about compatibility issues — as you would if you were writing JavaScript that would run in different browsers.
To illustrate the point, here’s a second program that makes use of several modern JavaScript features, such as tagged template literals, object destructuring and Array.prototype.flatMap(): function upcase(strings, ...values) { return values.map(name => name[0].toUpperCase() + name.slice(1)) .join(' ') + strings[2]; } const person = { first: 'brendan', last: 'eich', age: 56, position: 'CEO of Brave Software', }; const { first, last } = person; const emoticon = [ ['┌', '('], ['˘', ' ⌣ '], ['˘', ')', 'ʃ'] ]; console.log( upcase`${first} ${last} is the creator of JavaScript! ` + emoticon.flat().join('') ); Save this code to a file called index.js and run it from your terminal using the command node index.js. You should see Brendan Eich is the creator of
JavaScript! ┌( ˘ ⌣ ˘)ʃ output to the terminal. Introducing npm, the JavaScript Package Manager As I mentioned earlier, Node comes bundled with a package manager called npm. To check which version you have installed on your system, type npm - v. In addition to being the package manager for JavaScript, npm is also the world’s largest software registry. There are over 1,000,000 packages of JavaScript code available to download, with billions of downloads per week. Let’s take a quick look at how we would use npm to install a package. Installing a Package Globally Open your terminal and type the following: npm install -g jshint This will install the jshint package globally on your system. We can use it to lint the index.js file from the previous example: jshint index.js You should now see a number of ES6-related errors. If you want to fix them up, add /* jshint esversion: 6 */ to the top of the index.js file, re-run the command and linting should pass.
If you’d like a refresher on linting, see A Comparison of JavaScript Linting Tools. Installing a Package Locally We can also install packages locally to a project, as opposed to globally, on our system. Create a test folder and open a terminal in that directory. Next type this: npm init -y This will create and auto-populate a package.json file in the same folder. Next, use npm to install the lodash package and save it as a project dependency: npm install lodash --save Create a file named test.js and add the following: const _ = require('lodash'); const arr = [0, 1, false, 2, '', 3]; console.log(_.compact(arr)); Finally, run the script using node test.js. You should see [ 1, 2, 3 ] output to the terminal.
JavaScript and Node.js JavaScript and You Before we talk about the whole technical part, let's take a minute and talk about you and your relationship with JavaScript. This chapter is here to allow you to estimate whether or not it makes sense for you to continue reading this document. If you're like me, you started HTML "development" a long time ago, writing HTML documents. You ran into this cool thing called JavaScript,
but you only used it in a very basic way, adding interactivity to your pages from time to time. What you really wanted was "the real thing", you wanted to know how to build complex websites - You learned a programming language like PHP, Ruby, Java, and started writing "backend" code. However, you kept an eye on JavaScript, and realized that with the introduction of jQuery, Prototype, and others, things were getting more advanced in the JavaScript Lands, and that this language was really more than just making a window.open () . However, this was all about the frontend , and although it was nice to have jQuery at your disposal any time you felt like spicing up a web page, at the end of the day, which you were at the most, it was a user of JavaScript, but no, a JavaScript developer. And then Node.js. came JavaScript on the server, what about that? You decided it was time to check out the new JavaScript. But wait: Writing Node.js applications is one thing; Understanding why they need to be written the way they are means understanding JavaScript! And this time it is serious. And here's the problem: Since JavaScript actually lives two, or maybe three lives (The little DHTML helper of the mid-90's, the more serious things such as jQuery and the like, and now, the server side), it's not So easy to find information to help you learn JavaScript the "right way" so that you can write Node.js applications in a way that makes you feel that you are not only using JavaScript, but are also developing it.
Because therein lies the point: You are already an experienced developer, and you don't want to learn a new technique simply by putting code here and there by misusing it; You want to be sure that you are focusing at the correct angle. There is, of course, excellent documentation outside. But documentation alone is not enough. What is needed is a guide. My goal is to provide you with this guide. An advert There are some really great people at JavaScript. I am not one of them. I really am the type that I told you about in the previous paragraphs. I know a few things about developing backend applications, but I'm still new to "real" JavaScript and even newer to Node.js. I have only recently learned some of the advanced aspects of JavaScript. I am not experienced. So this is not a "novice to expert" book. This is rather a book "from novice to advanced novice". If I don't fail then this will be the type of document I wish I would have had when I started with Node.js. Server Side JavaScript
The earliest incarnations of JavaScript lived in browsers. But this is just the context. It defines what you can do with language, but it doesn't say much about what language itself can do. JavaScript is a "complete" language: You can use it in many contexts and achieve with it, everything you can achieve with any other "complete" language. Node.js really is just another context: it allows you to run JavaScript code in the backend, outside the browser. In order to execute the JavaScript code that you intend to run in the backend, it needs to be interpreted and, well, executed, This is what Node.js does, using Google's Virtual Machine V8, the same JavaScript execution environment that Google Chrome uses. Also, Node.js comes with many useful modules, so you don't have to write everything from scratch, such as something that puts a string to the console. So Node.js is actually two things: a runtime environment and a library. To make use of these (the library and the environment), you need to install Node.js. Instead of repeating the process here, please visit the official installation instructions . Please come back once you have your version of Node.js running.
"Hello World" Okay. So let's jump into the cold water and write our first Node.js application: "Hello World". Open your favorite editor and create a file called helloworld.js . We want to write "Hello World" to STDOUT, and here is the code needed to do this: console.log ("Hello World"); Save the file, and run it through Node.js: node helloworld.js It should return Hello World on your monitor. Ok, this is boring, okay? So let's write something real. A Complete Web Application with Node.js
Use cases Let's keep it simple, but realistic: The User should be able to occupy our application with a browser. The User should see a welcome page when requesting http: // domain / home, which displays an upload form. Choosing an image file to upload and submitting the form, the image should be uploaded to http: // domain / upload, where it is displayed once the upload is complete. Very good. Now, you may be able to achieve this goal by Googling and programming whatever , but that's not what we want to do here. More than that, we don't want to simply write the most basic code possible to achieve this goal, no matter how elegant and correct this code may be. We will intentionally add more abstraction than necessary so that we can get an idea of what it is to build more complex Node.js applications. The Application Stack Let's breakdown our app. What parts need to be implemented in order to satisfy our use cases? We want to serve web pages, so we need an HTTP Server . Our server will need to respond directly to requests (requests), depending on which URL is requested in this requirement, it is that we will need some type of router (router) in order to map the requests to their handlers.
To satisfy requests that came to the server and have been routed using the router, we will actually need request handlers The Router should probably process any POST information that comes in and give it to the request handlers in a convenient way, then we will need request data manipulation We not only want to handle requests for URLs, but we also want to display content when these URLs are requested, which means that we need some kind of logic in the views to be used by request handlers, in order to send content to the browser of the User. Last but not least, the User will be able to upload images, so we will need some kind of upload manipulation who will take care of the details. Let's think for a moment about how we would build this application stack with PHP. It is not exactly a secret that the typical configuration would be an Apache HTTP server with mod_php5 installed. Which in turn means that the topic "We need to be able to serve web pages and receive HTTP requests" doesn't even happen within PHP itself. Well, with Node.js, things are a little different. Because with Node.js, we not only implement our application, we also implement the entire full HTTP server. In fact, our web application and your web server are basically the same. This may sound like a lot of work, but we'll see in a moment that with Node.js, it isn't. Let's start at the beginning and implement the first part of our stack, the HTTP server.
Building the Application Stack A Basic HTTP Server When I got to the point where I wanted to start with my first "real" Node.js application, I wondered not only how I was going to program it, but also how to organize my code. Will I need to have it all in one file? Many web tutorials that teach you how to write a basic HTTP server in Node.js have all the logic in one place. What if I want to make sure that my code remains readable as I add more things to it? It turns out, it is relatively easy to keep the different aspects of your code separate, putting them in modules. This allows you to have a clean main file , in which you run Node.js, and clean modules that can be used by the main file among many others. So we are going to create a main file which we will use to start our application, and a module file where the code of our HTTP server will reside. My impression is that it is more or less standard to name your main file as index.js . It also makes sense that we put our server module in a file called server.js . Let's start with the server module. Create the server.js file in the root directory of your project, and fill it with the following code: var http = require ("http");
http.createServer (function (request, response) { response.writeHead (200, {"Content-Type": "text / html"}); response.write ("Hello World"); response.end (); }). listen (8888); That's! You just wrote an active HTTP server. Let's try it by running and testing it. First run your script with Node.js: node server.js Now open your browser and point it to http: // localhost: 8888 / . This should display a web page that says "Hello World". Interesting, right? How about we talk about what's going on here and leave the question of 'how to organize our project' for later? I promise we will come back to this. Analyzing our HTTP server Well then, let's analyze what is happening here. The first line require , requires the http module that comes bundled with Node.js and makes it accessible through the http variable . Then we call one of the functions that the http module offers: createServer . This function returns an object, and this object has a method called listen ,
Comments 0
Loading comments...
Reply to Comment
Edit Comment