Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the features of Node.js

2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the characteristics of Node.js". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the characteristics of Node.js"?

Why use Node

For me, for teams, the reason for Node is simple: it's fast to develop. Front-end students who are familiar with JS can get started quickly and save costs. Select a http server library to start a server, select the appropriate middleware, match the request route, and reasonably use the ORM library to link to the database, add, delete, modify and check.

Applicable scenarios for Node

Node.js uses an event-driven, non-blocking Istroke O model to make it lightweight and efficient. This model enables Node.js to avoid the loss of CPU time caused by waiting for input or output (database, file system, Web server, etc.) response. Therefore, Node.js is suitable to be used in scenarios with high concurrency, dense I-Pot O and a small amount of business logic.

Corresponding to the specific business at ordinary times, if it is an internal system, most of them just need to add, delete, modify and check a database, then the server side is a Node.js shuttle directly.

For online business, if the traffic is small and the business logic is simple, the server side can also use Node.js completely. For projects with huge traffic and high complexity, Node.js is generally used as the access layer, and the backstage students are responsible for implementing the service. As shown below:

What's the difference between JS,Node.js development and page development?

In the browser-side development of the page, is to deal with users, re-interaction, the browser also provides a variety of Web Api for our use. Node.js is mainly data-oriented. When a request is received, specific data is returned. This is the difference between the two in the business path. The real difference lies in the business model (business model, which is a word I came up with). Let's just show it in a picture.

When you develop a page, each user has a copy of JS code on his browser. If the code collapses under certain circumstances, it will only affect the current user, not other users, and the user can recover after a refresh. In Node.js, without opening multiple processes, all users' requests go into the same JS code, and only one thread is executing the JS code. If a user's request causes an error, the Node.js process dies and the server directly dies. Although there may be process guardians and suspended processes will be restarted, in the case of a large number of user requests, errors will be triggered frequently, and the server may hang up and restart constantly, which will affect the user experience.

The above is probably the biggest difference between Node.js development and front-end JS development.

Matters needing attention when developing Node.js

When a user accesses the Node.js service, if a request is stuck and the service cannot return the result for a long time, or the logic error causes the service to hang up, it will bring large-scale experience problems. The goal of the server side is to return data quickly and reliably.

Caching

Because Node.js is not good at dealing with complex logic (JavaScript itself is inefficient), if you want to use Node.js as the access layer, you should avoid complex logic. If you want to process the data quickly and return it, it is crucial to use caching.

For example, using Node to do React isomorphism straight out, renderToString this Api, can be said to be relatively heavy logic. If the complexity of the page is high, the renderToString will be fully executed for each request, which will take a long time for the thread to execute the code, increase the response time and reduce the throughput of the service. At this point, caching is very important.

The main way to implement caching: in-memory caching. It can be implemented using Map,WeakMap,WeakRef and so on. Refer to the following simple sample code:

Const cache = new Map (); router.get ('/ getContent', async (req, res) = > {const id = req.query.id; / / hit cache if (cache.get (id)) {return res.send (cache.get (id));} / / request data const rsp = await rpc.get (id); / / after a complex operation, processing data const content = process (rsp) / / set cache cache.set (id, content); return res.send (content);})

When using caching, there is a very important question: how to update the memory cache. One of the easiest ways to do this is to start a timer, delete the cache periodically, and reset the cache when the next request arrives. In the above code, add the following code:

SetTimeout (function () {cache.clear ();}, 1000 * 60); / / delete the cache once every 1 minute

If the server side is fully implemented by Node, you need to connect to the database directly with the Node side. If the data timeliness requirement is not too high and the traffic is not too high, you can use a similar model mentioned above, as shown in the following figure. This reduces the pressure on the database and speeds up the response speed of the Node.

In addition, you need to pay attention to the size of the memory cache. If you keep writing new data to the cache, the memory will get bigger and bigger and eventually burst. Consider using the LRU (Least Recently Used) algorithm for caching. Open up a piece of memory specifically as a cache area. When the cache size reaches the upper limit, the longest unused cache is eliminated.

The memory cache will all fail when the process is restarted.

When the backend business is complex, the access layer traffic and the amount of data is large, you can use the following architecture and independent memory caching service. The Node access layer fetches data directly from the cache service, and the backend service updates the cache service directly.

Of course, the architecture in the figure above is the simplest case, and in reality, distributed caching and cache consistency need to be considered. This is another topic.

Error handling

Due to the characteristics of the Node.js language, Node services are more error-prone. If something goes wrong, the impact is that the service is not available. Therefore, the handling of errors is very important.

The most common way to deal with errors is try catch. However, try catch cannot catch asynchronous errors. Asynchronous operations are very common in Node.js. Asynchronous operations mainly expose errors in callback functions. Look at an example:

Const readFile = function (path) {return new Promise ((resolve,reject) = > {fs.readFile (path, (err, data) = > {if (err) {throw err; / / catch cannot catch errors, which is related to Node's eventloop. / / reject (err); / / catch can capture} resolve (data);});} router.get ('/ xxx', async function (req, res) {try {const res = await readFile ('xxx');.} catch (e) {/ / capture error handling. Res.send;}})

In the above code, the error from throw in readFile cannot be caught by catch. If we replace throw err with Promise.reject (err), errors can be caught in catch.

We can Promise all asynchronous operations, and then use async, try, and catch to handle errors.

However, there is always something that will be left out. At this point, you can use process to catch global errors and prevent the process from exiting directly, causing subsequent requests to hang up. Sample code:

Process.on ('uncaughtException', (err) = > {console.error (`${err.message}\ n$ {err.stack}`);}); process.on (' unhandledRejection', (reason, p) = > {console.error (`Unhandled Rejection at: Promise ${p} reason: `, reason);})

For error capture in Node.js, you can also use the domain module. Now this module is no longer recommended, and I have not practiced it in the project, so I will not expand it here. The async_hooks module launched by Node.js in recent years is still in the experimental stage, so it is not recommended to use it directly in online environment. Only by doing a good job of process guardianship, starting multi-processes, repairing error alarms in time, developing good coding specifications and using appropriate frameworks, can we improve the efficiency and stability of Node services.

Thank you for your reading, the above is the content of "what are the characteristics of Node.js", after the study of this article, I believe you have a deeper understanding of the characteristics of Node.js, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report