You have heard of Node.js, but are not sure what it is, and don't know how it fits into your development process? Or, you may have heard of praise for Node and now wonder if you need to learn it. Maybe you are familiar with other backend technologies and want to understand the differences between Node. If this sounds like you, keep reading. In this article, I will explore Node.js and its main examples from a beginner-friendly high-level perspective. I'll look at the main use cases of Node, and the current landscape of Node and provide you with various starting points (for further reading) along the way. Note that throughout the article, I will use "Node" and "Node.js" alternately.
Key Points
What is Node.js?
There are many definitions on the Internet. Let's look at some popular definitions. Here's what it says on the project homepage: > Node.js® is a JavaScript runtime built on the V8 JavaScript engine of Chrome.
Stack Overflow provides:> Node.js is an event-based, non-blocking, asynchronous I/O runtime that uses Google's V8 JavaScript engine and libuv library.
Well, "event-based", "non-blocking", "asynchronous I/O" - it's hard to digest so much information at once. So let's deal with this from a different perspective, first focusing on another detail mentioned in these two descriptions - the V8 JavaScript engine.
V8 engine is an open source JavaScript engine that runs in Google Chrome and other Chromium-based web browsers, including Brave, Opera, and Vivaldi. It is designed with performance in mind and is responsible for compiling JavaScript directly into native machine code that the computer can execute. However, when we say that Node is built on the V8 engine, we are not saying that the Node program is executed in the browser. They are not. Instead, the creator of Node (Ryan Dahl) took the V8 engine and enhanced it with various features such as file system APIs, HTTP libraries, and many operating system-related utilities approaches. This means that Node.js is a program that we can use to execute JavaScript on our computers. In other words, it is a JavaScript runtime.
How to install Node.js?
In this section, we will install Node and write a few simple programs. We will also learn about npm, a package manager bundled with Node.
Many websites will recommend you visit the Node official download page and get Node binary files suitable for your system. While this works, I recommend using version manager instead. This is a program that allows you to install multiple versions of Node and switch between them at will. There are many advantages to using version manager. For example, it eliminates permission issues that may arise when using Node and npm and allows you to set a Node version for each project. If you want to use version manager, please refer to our quick tip: Install multiple versions of Node.js using nvm. Otherwise, get the correct binary files suitable for your system from the link above and install them.
You can check if Node is installed on your system by opening a terminal and typing node -v. If all goes well, you should see something like v12.14.1 displayed. This is the current version of LTS at the time of writing. Next, create a new file named hello.js and copy the following code:
console.log("Hello, World!");
This uses Node's built-in console module to display messages in a terminal window. To run this example, enter the following command:
node hello.js
If Node.js is configured correctly, "Hello, World!" will be displayed.
As shown in this compatibility table, Node provides excellent support for ECMAScript 2015 (ES6) and later. Since you are targeting only one runtime (specific version of the V8 engine), this means you can write JavaScript using the latest and most modern syntax. This also means you don't usually have to worry about compatibility issues - you'll run into this if you're writing JavaScript that will run in a different browser. To illustrate this, here is a second program that uses several modern JavaScript features such as tag template literals, object deconstruction, and Array.prototype.flatMap():
console.log("Hello, World!");
Save this code to a file named index.js and run it from the terminal using the command node index.js. You should see that Brendan Eich is the creator of JavaScript! ┌(˘⌣˘)ʃ output to the terminal.
Introduction to npm, JavaScript package manager
As mentioned earlier, Node comes with a package manager called npm. To check which version is installed on your system, type npm -v. In addition to being a JavaScript package manager, npm is also the world's largest software registration center. There are over 1,000,000 JavaScript code packages available for download, with billions of downloads per week. Let's take a quick look at how to install the package using npm.
Open your terminal and type the following:
node hello.js
This will install the jshint package globally on your system. We can use it to lint the index.js file in the previous example:
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('') );
You should now see many ES6-related errors. If you want to fix them, add /* jshint esversion: 6 */ to the top of the index.js file, rerun the command, and lint should pass. If you want to review lint, see Comparison of JavaScript Lint Tools.
We can also install the package locally into the project instead of globally to our system. Create a test folder and open a terminal in that directory. Next type the following:
npm install -g jshint
This will create and automatically fill the package.json file in the same folder. Next, install the lodash package using npm and save it as a project dependency:
jshint index.js
Create a file named test.js and add the following:
npm init -y
Lastly, run the script using node test.js. You should see [1, 2, 3] output to the terminal.
If you look at the contents of the test directory, you will notice a folder called node_modules. This is where npm saves any libraries that lodash and lodash depend on. The node_modules folder should not be checked in version control, and in fact, it can be recreated at any time by running npm install in the root of the project. If you open the package.json file, you will see lodash listed under the dependencies field. By specifying the project's dependencies this way, you can allow any developer anywhere to clone your project and run all the packages you need with npm installation. If you want to learn more about npm, be sure to read our article npm beginner’s guide – Node Package Manager.
What is Node.js used for?
Now that we already know what Node and npm are and how to install them, we can turn our attention to one of their common uses: install (via npm) and run (via Node) a variety of build tools – designed to automate The development process of modern JavaScript applications. These build tools are so diverse that in modern JavaScript environments you can't go too far without encountering them. They can be used for anything, from bundling your JavaScript files and dependencies to static assets, to running tests, or automatic code lint and style checking. We have many articles on SitePoint to describe building tools. Here are some of my favorite articles:
If you want to start developing applications using any modern JavaScript framework such as React or Angular, you need to have working knowledge of Node and npm (or Yarn). This is not because you need the Node backend to run these frameworks. You don't need it. It's because these frameworks (and many related packages) are available through npm and rely on Node to create a reasonable development environment so that they can run in it. If you are interested in understanding what role Node plays in modern JavaScript applications, read the analysis of modern JavaScript applications.
Node.js allows us to run JavaScript on the server
Next, let's look at one of the biggest use cases of Node.js - running JavaScript on a server. This is not a new concept, and it was first tried by Netscape in 1994. However, Node.js is the first implementation to gain any real appeal, and it offers some unique advantages over traditional languages. Node now plays a key role in the technology stacks of many well-known companies. Let's see what these benefits are.
Very simply, when you connect to a traditional server (such as Apache), it generates a new thread to handle the request. In languages such as PHP or Ruby, any subsequent I/O operations (for example, interacting with a database) block the execution of the code until the operation is completed. That is to say, the server must wait for the database search to complete before continuing to process the results. If new requests come in during this time, the server will generate new threads to process them. This can be inefficient because a large number of threads can cause the system to become slow - at worst, the website will be down. The most common way to support more connections is to add more servers.
However, Node.js is single-threaded. It is also event-driven, which means that everything that happens in Node is a reaction to events. For example, when a new request comes in (an event), the server will start processing it. If it then encounters a blocking I/O operation, it does not wait for the operation to complete, but registers a callback before proceeding with the next event. When the I/O operation completes (another event), the server executes a callback and continues to process the original request. In the background, Node uses the libuv library to implement this asynchronous (i.e., non-blocking) behavior. Node's execution model makes the server almost no overhead, so it can handle a large number of concurrent connections. The traditional way to scale a Node application is to clone it and have the cloned instances share the workload. Node.js even has a built-in module to help you implement cloning policies on a single server. The following figure describes the execution model of Node:
Source: Introduction to Node.js by Professor Christian Maderazo and James Santos
Or, if you like videos, check out this wonderful speech: What exactly is the event loop? It's not unique to Node, but it explains the concept very well.
The fact that Node runs in a single thread does bring some limitations. For example, blocking I/O calls should be avoided, CPU-intensive operations should be handed over to the worker thread, and errors should always be handled correctly to avoid crashing the entire process. Some developers also don't like the callback-based coding style imposed by JavaScript (so much so that there is even a website dedicated to the horrors of writing asynchronous JavaScript). But with the arrival of native Promise, followed by async await, process control in modern JavaScript is easier than ever.
Let's take a quick look at the "Hello, World!" HTTP server example:
console.log("Hello, World!");
To run this code, copy the code into a file named hello-world-server.js and run it with node hello-world-server.js. Open the browser and navigate to https://www.php.cn/link/4a914e5c38172ae9b61780ffbd0b2f90 to view "Hello, World!" displayed in the browser. Now let's take a look at the code. We first need the native HTTP module of Node. We then use its createServer method to create a new web server object, and we pass an anonymous function to it. This function will be called for each new connection established with the server. Anonymous functions are called with two parameters (request and response). These contain requests and responses from users, which we use to send 200 HTTP status codes as well as our "Hello World!" message. Finally, we tell the server to listen for incoming requests on port 3000 and output a message to the terminal to let us know that it is running. Obviously there is more to create or even a simple server in Node (for example, it is very important to handle errors correctly), so if you want to know more, I recommend you check the documentation or check out our tutorial.
What kind of application is Node.js suitable?
Node is especially suitable for building applications that require some form of real-time interaction or collaboration—for example, applications like chat sites or CodeShare, where you can watch other people edit documents in real time. It is also suitable for building APIs where you handle many I/O-driven requests (such as requests that require operations on a database), or websites involving data flows, because Node allows you to process files while they are still uploading. If this real-time aspect of Node is what you want to know more about, check out our tutorial on building a live chat application. However, not everyone will build the next Trello or the next Google Docs, and in fact, there is no reason you can't use Node to build a simple CRUD application. However, if you follow this route, you will soon find that Node is very basic and the way you build and organize your applications is largely up to you. You can use a variety of frameworks to reduce boilerplate code, where Express has established itself as a leader. However, even solutions like Express are minimal, meaning that if you want to do something slightly unusual you need to introduce other modules from npm. This is in stark contrast to frameworks like Rails or Laravel, which offers many features out of the box. If you want to learn how to build a basic, more traditional application, check out our tutorial on how to build and organize a Node.js MVC application.
What are the advantages of Node.js?
Aside from speed and scalability, a often mentioned advantage of using JavaScript in web servers and browsers is that your brain no longer needs to switch modes. You can do all the work in the same language, as a developer, which makes you more efficient (and hopefully happier). For example, you can easily share code between server and client. Another important advantage of Node is that it uses JSON. JSON is probably the most important data exchange format on the web and is also a common language for interacting with object databases, such as MongoDB. JSON is perfect for JavaScript programs, which means that when you use Node, data flows smoothly between layers without reformatting. You can use a syntax from your browser to your server to your database. Finally, JavaScript is everywhere: Most of us are familiar with JavaScript, or have used it at some point. This means that transitioning to Node development may be easier than transitioning to other server-side languages. To quote Craig Buckler in his Node vs. PHP showdown, JavaScript is probably the most misunderstood language in the world—but once the concept is clicked, it makes other languages appear clumsy.
Other uses of Node
It doesn't stop at the server. Node.js has many other exciting and varied uses! For example, it can be used as a scripting language to automatically perform repetitive or error-prone tasks on your PC. It can also be used to write your own command line tools, such as this Yeoman-style generator to build new projects. Node.js can also be used to build cross-platform desktop applications, and even to create your own bots. What else do you don't like?
Conclusion
JavaScript is everywhere, and Node is also a huge and extensive topic. Nevertheless, I hope in this article, I have provided you with a beginner-friendly advanced perspective on Node.js and its main examples that begin with. I also hope that things will make more sense when you reread the definitions we saw before.
Node.js is an event-based, non-blocking, asynchronous I/O runtime that uses Google's V8 JavaScript engine and libuv library.
If you have any questions or comments, feel free to contact me on Twitter.
FAQs about Node.js
JavaScript is a programming language mainly used for client-side web development. It is a language that runs in the browser. Node.js, on the other hand, is a runtime environment that allows JavaScript to run on the server side. It is built on Chrome's V8 JavaScript engine. Node.js extends the capabilities of JavaScript to enable it to interact with the I/O API, perform network functions, and access databases, which are usually not available in browser-based JavaScript.
Node.js is very popular in server-side programming due to its non-blocking, event-driven architecture. This means it can handle multiple client requests simultaneously without waiting for tasks such as network requests or database operations to complete. This makes Node.js efficient and suitable for real-time applications such as chat applications, collaboration tools, and gaming servers.
Node.js uses its event-driven, non-blocking I/O model to handle concurrent requests. When a request is made, Node.js performs the action and then proceeds to the next request without waiting for the previous action to complete. After the operation is completed, an event will be triggered and the corresponding callback function will be executed. This allows Node.js to handle thousands of concurrent connections using a single server.
Although Node.js is mainly used for server-side development, it can also be used for front-end development. Node.js provides tools and frameworks, such as Express.js and Socket.IO, for building powerful front-end applications. Additionally, Node.js is used to run build tools such as Babel and Webpack, which are essential in modern front-end development.
NPM or Node package manager is an indispensable tool in Node.js development. It is a package manager that allows developers to install, update, and manage the various libraries and dependencies required by Node.js applications. NPM provides a large open source package repository that makes it easier for developers to share and reuse code.
Node.js differs from PHP and Ruby on Rails in several ways. Unlike synchronous PHP and Ruby on Rails, Node.js is asynchronous and non-blocking, meaning it can handle multiple requests simultaneously. This makes Node.js more efficient and suitable for real-time applications. Additionally, Node.js uses JavaScript, a language that many developers are familiar with, thus reducing the learning curve.
Node.js has a variety of functions and can be used in various applications. It is especially suitable for building scalable web applications, real-time applications such as chat applications and game servers, collaboration tools and API servers. Companies like Netflix, LinkedIn, and Uber use Node.js in their technology stacks because it is efficient and fast.
While Node.js provides many benefits, it also faces some challenges. Its asynchronous, non-blocking nature can make code difficult to understand and debug. Additionally, since Node.js is single-threaded, CPU-intensive tasks can block the entire server, affecting performance. However, these challenges can be mitigated with good coding practices and proper use of tools and libraries.
Node.js handles errors through the first error callback. This means that the first parameter passed to the callback function is an error object. If an error occurs during the asynchronous operation, it is passed as the first parameter to the callback function. If no error occurs, this parameter will be null.
Yes, Node.js can interact with various types of databases, including SQL and NoSQL databases. Several libraries and ORMs (Object Relational Mapping) are available, such as Sequelize for SQL databases and Mongoose for MongoDB, which make it easier to interact with a database in a Node.js application.
All picture formats remain as .jpg
or .webp
.
The above is the detailed content of An Introduction to Node.js. For more information, please follow other related articles on the PHP Chinese website!