In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces you how to understand the role of the Util module in node.js, the content is very detailed, interested friends can refer to, hope to be helpful to you.
Starting from the type judgment
Type checking of variables is a big headache in JavaScript, and there are all sorts of problems if you simply use typeof.
Here are a few simple ones:
Console.log (typeof null) / / 'object'console.log (typeof new Array) / /' object'console.log (typeof new String) / / 'object'
Later, it was discovered that the Object.prototype.toString () method could be used to determine the type of variable.
Const getTypeString = obj = > Object.prototype.toString.call (obj) getTypeString (null) / /'[object Null] 'getTypeString (' string') / /'[object String] 'getTypeString (new String) /' [object String]'
By proxying the toString () method, you get a type string, and we can make trouble on that string.
Const getTypeString = obj = > {return Object.prototype.toString.call (obj)} const isType = type = > {return obj = > {return getTypeString (obj) = `[object ${type}]`} const isArray = isType ('Array') / / this method is usually replaced by Array.isArray instead of const isNull = isType (' Null') const isObject = isType ('Object') const isRegExp = isType (' RegExp') const isFunction = isType ('Function') const isAsyncFunction = isType (' AsyncFunction') IsNull (null) / / trueisObject ({}) / / trueisRegExp (/\ w/) / / trueisFunction (() = > {}) / / trueisAsyncFunction (async () = > {}) / / true
But, in Node.js, there is actually a set of api used to determine the type of variable. And extremely rich in functions, in addition to the basic type of judgment, but also supports the judgment of Promise objects, Date objects, various ArrayBuffer.
Const types = require ('util/types') types.isDate (new Date) / / truetypes.isPromise (new Promise (() = > {})) / / truetypes.isArrayBuffer (new ArrayBuffer (16)) / / true is strictly equal
In JavaScript, objects, arrays, and other variables in the process of judging equality, if you use = will usually only determine whether the two variables point to the same memory address. If you want to determine whether all the values corresponding to the keys of an object are equal, you need to traverse the two objects. In util, a method is also provided to determine whether two objects are strictly equal: util.isDeepStrictEqual (val1, val2)
Const util = require ('util') const val1 = {name:' shenfq'} const val2 = {name: 'shenfq'} console.log (' val1 = = val2', val1 = val2) / / falseconsole.log ('isDeepStrictEqual', util.isDeepStrictEqual (val1, val2)) / / true
This method can also be used to determine whether an array is strictly equal:
Const util = require ('util') const arr1 = [1,3,5] const arr2 = [1,3,5] console.log (' arr1 = = arr2', arr1 = arr2) / / falseconsole.log ('isDeepStrictEqual', util.isDeepStrictEqual (arr1, arr2)) / / trueError First & Promise
The early Node API is Error First-style, that is, all asynchronous functions accept a callback function, and one parameter of the callback is the error object. If the normal returned error object is null, the subsequent parameters are the result of a successful response.
/ / the following is an example of reading a file const fs = require ('fs') fs.readFile (' nginx.log', (error, data) = > {if (error) {/ / failed to read the file console.error (error) return} / / read the file successfully, and the print result console.log (data)})
When Node 8 was released, a new promisify interface was added to convert Error First-style API to Promise API.
Const fs = require ('fs') const util = require (' util') const readFile = util.promisify (fs.readFile) readFile ('. / 2021-11-11.log, {encoding: 'utf-8'}) .then (text = > console.log (text)) .catch (error = > console.error (error))
However, many people later found that the way these native API supports Promise is too cumbersome, and each API needs to wrap a separate layer of promisify methods. When Node 10 was released, the native module added a .attributes attribute under which all API were Promise-style.
Const fs = require ('fs'). Promisesfs.readFile ('. / 2021-11-11. Log, {encoding: 'utf-8'}) .then (text = > console.log (text)) .catch (error = > console.error (error))
Note: after Node 14, promises API has added a new way to introduce it by changing the package name.
Const fs = require ('fs/promises') fs.readFile ('. / 2021-11-11. Log, {encoding: 'utf-8'}) .then (text = > console.log (text)) .catch (error = > console.error (error))
In addition to converting Error First-style API to Promise API,util, there is also a callbackify method for converting async functions into Error First-style functions.
Let's restore the promise fs to an Error First-style function through callbackify.
Const fs = require ('fs/promises') const util = require (' util') const readFile = util.callbackify (fs.readFile) readFile ('. / 2021-11-12.log, {encoding: 'utf-8'}, (error, text) = > {if (error) {console.error (error) return} console.log (text)}) debugging and output
If you have developed Node services, you should all have used the debug module, through which you can see clearer debugging information on the console.
Const debug = require ('debug') const log = debug (' app') const user = {name: 'shenfq'} log (' current user:% oPCll, user)
In fact, a similar effect can be achieved through util.debug:
Const debug = require ('debug') const log = debug (' app') const user = {name: 'shenfq'} log (' current user:% oPCll, user)
It's just that at startup, you need to replace the DEBUG environment variable with NODE_DEBUG.
If you take a closer look at the above code, you should find that there is a% o placeholder in the string in front of the log ('current user:% ovoid, user) method, indicating that this place will be populated with an object (object). This is similar to printf in C or python. Similarly, in the util module, a formatting method is provided directly: util.format.
Const {format} = require ('util') console.log (format (' current user:% current, {name: 'shenfq', age: 25}))
In addition to% o placeholders, different data types should use different placeholders.
Placeholder type s string d digits (including integers and floating point numbers) I integer f floating point jJSON%oObject
Objects in JavaScript are very complex. In addition to formatting objects directly with util.format plus% o placeholders, util also provides a method called inspect to format objects.
Const {inspect} = require ('util') const user = {age: 25, name:' shenfq', work: {name: 'coding', seniority: 5}} console.log (inspect (user))
In this way, inspect doesn't seem to have done anything, but the inspect method has a second parameter for some personalized configuration when formatting.
Depth: number: controls the display level
Sorted: boolean | Function: whether to sort by the coding value of key
Compact: boolean: whether to display in a single line
Of course, the above is only part of the configuration. For more detailed configuration, please refer to the node documentation. Here are some examples:
All properties are displayed on a new line:
Inspect (user, {compact: false})
Format only the values of the first layer of the object:
Inspect (user, {depth: 0, compact: false})
Output in reverse order according to the coding of key values:
Inspect (user, {compact: false, sorted: (a, b) = > a < b? 1:-1}) so much about how to understand the role of the Util module in node.js. I hope the above content can be helpful to you and 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.