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

How to be a better Node.js developer

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

Share

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

This article introduces you how to become a better Node.js developer, the content is very detailed, interested friends can refer to, hope to be helpful to you.

The editor mainly discusses some practices and suggestions for Node.js development, which are not only suitable for developers, but also for those who manage and maintain the Node.js infrastructure. Following these suggestions in this article will enable you to better carry out your daily development work.

Callback convention, which also supports Promise

Last year, we might recommend you to expose errors for your module as a priority callback interface. But with the formal standardization of generator functions and asynchronous functions coming, we now recommend that you expose error-first callbacks that support Promise when writing module interfaces.

Why do you need this? First of all, the callback interface is to provide backward compatibility, in order to achieve better compatibility in the future, we need to provide Promise support at the same time.

You can refer to the following example to further understand how to program. In this example, the readPackage function reads the package.json file and returns its contents through both the Promise and callback interfaces.

Const fs = require ('fs'); function readPackage (callback) {/ / as of now we do not have default values in Node.js callback = callback | | function () {} return new Promise ((resolve, reject) = > {fs.readFile ('. / package.json', (err, data) = > {if (err) {reject (err); return callback (err);} resolve (data); return callback (null, data) })}} module.exports.readPackage = readPackage

Asynchronous mode

In Node.js, for a long time you had only two ways to manage asynchronous flows: callbacks or Stream. For callback functions, you can use libraries like async, and for streams, there are libraries such as through, bl, highland, and so on.

However, as Promise, generator and asynchronous functions are gradually introduced into the standard ECMAScript,JS, the process control has been greatly improved.

Error handling

Error handling plays a vital role in application development: it is difficult to determine when the application crashes or just print error messages to ensure that the application continues to run.

In order to explain this problem more simply, we decided to divide it into two categories: programmer errors (programmer errors) and operational errors (operational errors).

Programmer error is what we call bug, because you do not know the exact state of the program running, so when there is an error, you immediately stop running the application (crash the process).

On the other hand, computational errors are caused by the system or the remote service itself. For example: request timeout and insufficient memory and so on. Based on the characteristics of the error, you can prescribe the right medicine to the case, and then try again, for example, if the file is missing, you can create the corresponding file.

Error handling in callback

If an error occurs during an asynchronous operation, the error object should be passed as the first parameter of the asynchronous function. You must always check the error object and handle the error.

The previous example of callback conventions has shown how to give priority to errors in callback functions.

Error handling in Promise

What happens if it is the following code snippet?

Promise.resolve (() = > 'John') .then (() = > {throw new Error (' ops');}) .catch ((ex) = > {console.log (ex);}). Then () = > {throw new Error ('ups'); console.log (Doe');})

An exception is thrown on line 3.

Catch will process it and print out in stdout: [Error: ops]

Execution continues, and a new error is thrown at line 9

It's gone.

It's really nothing; the first mistake thrown will be silent. You need to note that you should always use a catch statement as the first link of the promise chain. This will solve many headaches for you. Like this:

Promise.resolve (() = > 'John') .then (() = > {throw new Error (' ops');}) .catch ((ex) = > {console.log (ex);}) .then (() = > {throw new Error ('ups'); console.log (Doe');}) .catch ((ex) = > {console.log (ex);})

The following will now be output:

[Error: ops] [Error: ops]

Use JavaScript standard style

Over the past few years, we have used very useful code quality tools such as JSHint, JSCS, ESLint, and so on to automate the inspection of our code as much as possible.

Recently, when it comes to code style, we use feross's JavaScript standard style.

The reason is that it is very simple: you don't need any configuration files, you just need to put them in the project. It mainly includes the following rules:

Use 2 spaces as indentation

Strings use single quotation marks-except to avoid escaping

Do not include variables that are not used

No semicolon

Never start a line with (or [)

Keyword followed by a space if (condition) {.}

The function name is followed by a space function name (args) {.}

Always use = = instead of = =, but you can use obj = = null to check null | | undefined.

Always deal with the err function parameters of Node.js

Always add window prefixes to browser global variables, except for document and navigator

Avoid using global variables such as open, length, evet, name, and so on, whenever possible.

Of course, if your editor only supports ESLint, there is an ESLint rule base for using the standard style, eslint-plugin-standard. After installing this plug-in, your .eslintrc file can look like this:

{"plugins": ["standard"],}

12-Factor Application (The Twelve-Factor Application)

Today, software is usually delivered as a service, and they are called web applications, or software as a service (SaaS). The 12-Factor Application Manifesto describes the practice of developing Web applications:

Benchmark code: one benchmark code, multiple deployments

Dependencies: displaying declared dependencies

Configurations: storing configurations in the environment

Back-end services: treat back-end services as additional resources

Build, release, run: strictly separate build and run

Processes: running applications as one or more stateless processes

Port binding: providing services through port binding

Concurrency: extending through the process model

Easy to handle: quick start and graceful termination can make you more robust

The development environment is equivalent to the online environment: keep the development, pre-release and online environment the same as possible

Logs: treat logs as a stream of events

Management process: back-end management tasks run as an one-time process

This theory applies to applications developed in any language and back-end services (database, message queue, cache, etc.).

Start a new project

Always start a new project with the npm init command. This creates an initial package.json for your project.

If you want to skip the initial question and use the default configuration directly, just run npm init-yes.

Monitor your app

When a failure occurs or is about to happen, timely notification can recover the loss for you.

For monitoring applications, you can use similar SaaS products or open source software. In terms of open source software, it mainly includes: Zabbix, Collected, ElasticSearch and Logstash.

If you don't want to deploy on your own, consider using online services. You can try using Trace, a Node.js and micro-service monitoring solution developed by our company.

Semantic version control is a formal agreement for the use of three-segment version numbers for compatibility, namely: major.minor.patch, major version, minor version, and patch.

Use the major version number if it is an API change that is not backward-compatible compatible. The minor version number is used when a new feature is added and the API change is backward compatible. If you are only repairing Bug, you can use the package version number.

Fortunately, you can use the semantic-release module to automate the release of your JavaScript modules.

On how to become a better Node.js developer to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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