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

Share minority but useful Node.js packages

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "sharing minority but useful Node.js package". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "sharing minority but useful Node.js package".

Yargs

Yargs is a package for handling command-line parameters that can help you with self-set command-line flags and any type of data entered, including Boolean values, floating-point numbers, strings, and so on. This package is very simple and straightforward and does not require a lot of boilerplate code to be written in the project.

Yargs can help you with the usage help output and can easily tell users which options to enter when using your program, including which are required.

Var argv = require ('yargs') .usage (' Usage: $0-x [num]-y [num]') .demand (['x games pagey']) .argv; console.log ('Pow (x, y):', Math.pow (argv.x, argv.y))

Save the above code as index.js, then execute node index.js-x 3 on the command line, and you will see the following message:

Usage: index.js-x [num]-y [num] Options:-x [required]-y [required] Missing required argument: y

Yargs can tell us exactly what parameters are missing on the command line, and we just need to simply call the .usage () and .demand () methods.

Toobusy

This is a very practical bag. It polls the Node event loop and tracks the time it takes to complete the request. If the delay is too long, toobusy will notify you, and then you can return the HTTP 503 "Service Unavailable" status code to the client.

This processing is important because the busier the server is, the longer the request waits. This will soon become a very complex problem, and it will become more and more serious as time goes by. If you let it go, the service will collapse. If we can stop processing some requests in time and return HTTP 503, at least some requests can be processed.

You can easily install toobusy with the npm command:

Npm install toobusy

Then integrate it with something like Express:

Var toobusy = require ('toobusy'), express = require (' express'); var app = express (); / / if the server is under too much pressure, the request app.use (function (req, res, next) {if (toobusy ()) {res.send (503, "Too many users!");} else {next ();}}); var server = app.listen (3000) Process.on ('SIGINT', function () {server.close (); toobusy.shutdown (); / / normal exit process.exit ();})

We don't need to write much code or too much configuration to inherit into our own project.

Chalk

It is difficult to develop a useful user interface on the command line because it is only the command line window that is used to interact with the user. So how do you prompt for some important information? It is a good way to add formatting to the output text. Express is a typical example, from its output, you can easily read quickly to find important information.

The following is a list of styles supported by chalk:

Modifier bold

Underline

Dim

Reset

Hidden

Inverse

Italic (not supported by all environments)

Strikethrough (not supported in any environment)

Color

Red

Black

Green

White

Yellow

Blue (brighter version will be used on Windows because plain blue is difficult to recognize)

Cyan

Gray

Magenta

Background color

BgBlue

BgBlack

BgRed

BgGreen

BgCyan

BgYellow

BgWhite

BgMagenta

Although officially only these colors are supported, any terminal that complies with the xterm standard can use a complete 8-bit color code.

You can easily format the text simply by passing the string to the function used for coloring or formatting. If you need to draw the user's attention to serious errors, you can use the following format:

Var chalk = require ('chalk'); var str = chalk.red.bold (' ERROR:') + chalk.bold ('Everything just blew up...'); console.log (str)

Node-inspector

Easy-to-use debuggers are hard to find, especially those with a good GUI. Node-inspector provides you with a web GUI to help debug your code. It has all the features of a standard debugger, such as breakpoints, stepping, exit code, and variable checking, as well as some less commonly used features, but these features are very useful, such as CPU and heap analysis, network client request checking, and real-time editing of running code.

Node-inspector

However, node-inspector is only compatible with Chrome and Opera because it uses Blink Developer Tools and is compatible with Node.

I've always relied heavily on console output for debugging, which takes a lot of time. Using GUI can greatly save debugging time.

Terminal-kit

If your Node program needs to support anything other than simple text input and output from the command line, then you should need terminal-kit. Terminal-kit simplifies many things that interact with users, allowing you to focus on developing important content in your program. The main functions of terminal-kit are:

Text style (much like chalk)

Edit screen

Progress bar

User input

There are many examples suitable for terminal toolkits. For example, if you need to download some content from the Internet, you need to display a progress bar to the user. The following code displays the virtual progress bar:

Var terminal = require ('terminal-kit'). Terminal; var progressBar; var progress = 0; function updateProgress () {/ / generate a random progress value progress + = Math.random () / 10; progressBar.update (progress); / / check whether if (progress > = 1) {setTimeout (function () {terminal ('\ n'); process.exit ()) Else {setTimeout (updateProgress, 100 + Math.random () * 500);}} progressBar = terminal.progressBar ({width: 80, title: 'Downloading file:', eta: true, percent: true}); updateProgress ()

The above code produces the following effect:

Terminal-kit progress bar

Validator

Validator can help you with a series of common string verification (e. G. email address, phone number, IP address, etc.). Such a package is essential whenever you get input from the user. Users make mistakes and type something very strange in the text box, so you need a package to validate the input to avoid data corruption or server crash.

Here are some commonly used validators:

IsEmail (str [, options])

IsIP (str [, version])

IsMobilePhone (str, locale)

IsURL (str [, options])

Validator also provides detectors that can normalize, delete, or escape input strings. For example, clean up the content submitted by users to prevent them from entering malicious HTML or JavaScript code.

Here are some common detectors:

Blacklist (input, chars)

Escape (input)

NormalizeEmail (email [, options])

Whitelist (input, chars)

The normalizeEmail () method ensures that e-mail addresses are lowercase letters and can even delete characters that need to be ignored. Suppose you have an email that abc.def+ghi@163.com,normalizeEmail () will standardize as abcdefghi@163.com.

Formidable

Formidable can help you with every step of uploading files, including multi-part parsers, writing files to disk, and error handling. This is my favorite bag. If you don't want to reinvent the wheel, you can give it a try.

The following is an example of using formidable on a normal HTTP server, with the code modified from the example given in the package itself:

Var http = require ('http'); var util = require (' util'); var formidable = require ('formidable'); var path = require (' path'); var PORT = 8080; var root = path.join (_ _ dirname,'.. /'); exports.dir = {root: root, lib: root +'/ lib', fixture: root +'/ test/fixture', tmp: root +'/ test/tmp',} Var server = http.createServer (function (req, res) {if (req.url = ='/') {res.writeHead (200,{ 'content-type':' text/html'}); res.end ('+')

'+'

'+' +');} else if (req.url = ='/ post') {var form = new formidable.IncomingForm (), fields = []; form .on ('error', function (err) {res.writeHead (200,{' content-type': 'text/plain'}); res.end (' error:\ n\ n' + util.inspect (err)) ) .on ('field', function (field, value) {console.log (field, value); fields.push ([field, value]);}) .on (' end', function () {console.log ('> post done'); res.writeHead (200,{ 'content-type':' text/plain'}) Res.end ('received fields:\ n\ n' + util.inspect (fields));}); form.parse (req);} else {res.writeHead (404, {' content-type': 'text/plain'}); res.end (' 404');}}); server.listen (PORT); console.log ('listening on http://localhost:' + PORT +' /')

Shelljs

Shelljs is a package that allows you to use general Unix commands on any system, whether it's Windows, Linux, or Mac. So you don't have to write bash and batch scripts for the project. Shelljs provides a Unix-like environment, and if you need to write scripts to run tests, commit code, or start on the server, you only need to write once.

You can do something similar with the command:

Require ('shelljs/global'); ls (' * .js') .forEach (function (file) {sed ('- REMOVE_THIS_LINE.*, 'BUILD_VERSION',' v2.0.3march, file); sed ('- ifold, /. * REMOVE_THIS_LINE.*\ nREMOVE_THIS_LINE.*,', file); sed ('- ifold, /. * REPLACE_THIS_LINE.*\ nUnip, cat ('macro.js'), file);})

Execute common commands:

Require ('shelljs/global'); mkdir ('-paired, 'release/data'); cp ('-release/data', 'data/*',')

Check the available binaries:

Require ('shelljs/global'); if (! which (' git')) {echo ('This script requires gituals'); exit (1);}

You can even run the command as you would in a bash script:

If (exec ('git commit-am "Release commit"). Code! = = 0) {echo (' Error: Git commit failed packages'); exit (1);} Thank you for reading, the above is the content of "sharing minority but useful Node.js packages". After the study of this article, I believe you have a deeper understanding of the problem of sharing minority but useful Node.js packages, 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