YouTip LogoYouTip

Nodejs Util Module

[![Image 1: Java File](#)Node.js Built-in Modules](#) * * * The `util` module in Node.js is a core module that provides a series of utility functions. These functions are primarily designed to help developers accomplish common programming tasks, such as type checking, implementing inheritance, debugging output, etc. The original design intent of the `util` module was to compensate for the shortcomings of JavaScript's native features, providing developers with more convenience. To use the `util` module, you simply need to require it in your code: const util = require('util'); * * * ## Main Features of the util Module ### 1. Type Checking Tools The `util` module provides several functions for type checking, which are more precise and useful than JavaScript's native `typeof` operator. #### util.types.isArrayBuffer(value) Checks whether the given value is an ArrayBuffer instance. ## Example const arrBuffer =new ArrayBuffer(8); console.log(util.types.isArrayBuffer(arrBuffer));// true console.log(util.types.isArrayBuffer([]));// false #### util.types.isDate(value) Checks whether the given value is a Date instance. ## Example console.log(util.types.isDate(new Date()));// true console.log(util.types.isDate('2023-01-01'));// false ### 2. Utility Functions #### util.format(format[, ...args]) Similar to the `printf` function in C language, used to format strings. ## Example const name ='John'; const age =30; console.log(util.format('My name is %s and I am %d years old', name, age)); // Output: My name is John and I am 30 years old #### util.inspect(object[, options]) Returns a string representation of the object, primarily used for debugging. Options such as depth and colors can be configured. ## Example const obj ={ name:'Alice', details:{ age:25, hobbies:['reading','coding'] } }; console.log(util.inspect(obj,{ depth:2, colors:true})); ### 3. Callback Style Conversion #### util.promisify(original) Converts a function following the Node.js callback style into a function returning a Promise. ## Example const fs = require('fs'); const readFile = util.promisify(fs.readFile); async function readConfig(){ try{ const data = await readFile('config.json','utf8'); console.log(data); }catch(err){ console.error('Error reading file:', err); } } readConfig(); #### util.callbackify(original) The opposite of `promisify`, converts a function returning a Promise into a callback-style function. ## Example async function asyncFunc(){ return'Hello World'; } const callbackFunc = util.callbackify(asyncFunc); callbackFunc((err, result)=>{ if(err)throw err; console.log(result);// Hello World }); ### 4. Inheritance Tools #### util.inherits(constructor, superConstructor) Implements prototypal inheritance (ES5 style). Note: In ES6, it is recommended to use the `class` and `extends` keywords. ## Example function Animal(name){ this.name= name; } Animal.prototype.speak=function(){ console.log(this.name+' makes a noise.'); }; function Dog(name){ Animal.call(this, name); } util.inherits(Dog, Animal); Dog.prototype.speak=function(){ console.log(this.name+' barks.'); }; const d =new Dog('Rex'); d.speak();// Rex barks. * * * ## Practical Application Scenarios of the util Module ### 1. Debugging Complex Objects When you need to print the structure of complex objects, `util.inspect` is more powerful than a simple `console.log`: ## Example const complexObj ={ date:new Date(), regex:/test/g, nested:{ array:[1,2,3], fn:function(){} } }; console.log(util.inspect(complexObj,{ showHidden:true, depth:null, colors:true })); ### 2. Modernizing Legacy Code Converting old callback-style code to Promise style: ## Example // Old callback-style code function oldStyleFunc(param, callback){ // Some asynchronous operation setTimeout(()=>{ callback(null, `Result for ${param}`); },100); } // Convert to Promise style const newStyleFunc = util.promisify(oldStyleFunc); async function useNewStyle(){ const result = await newStyleFunc('test'); console.log(result);// Result for test } useNewStyle(); ### 3. Custom Object Inspection You can customize the `inspect` method of an object to change the output of `util.inspect`: ## Example class CustomObject { constructor(value){ this.value= value; } [util.inspect.custom](depth, options){ return `CustomObject: ${this.value}`; } } const obj =new CustomObject('test'); console.log(util.inspect(obj));// CustomObject: test * * * ## Notes 1. **Performance Considerations**: `util.inspect` may have performance impacts on large objects, so it should be used with caution in production environments. 2. **API Stability**: Although the `util` module is a core module, some APIs may still be marked as experimental features. 3. **Modern Alternatives**: Some features (like `util.inherits`) have better alternatives in modern JavaScript (such as the `class` syntax). 4. **Error Handling**: When using `promisify`, ensure that errors are handled correctly to avoid uncaught Promise rejections. * * * ## Methods and Properties | Method/Property | Description | Version Introduced | | --- | --- | --- | | **util.callbackify(original)** | Converts an async function returning a Promise into a callback-style function | 8.2.0 | | **util.debuglog(section)** | Creates a function that only logs messages when the NODE_DEBUG environment variable contains the specified section | 0.11.3 | | **util.deprecate(fn, msg[, code])** | Wraps a function so that it emits a deprecation warning when called | 0.8.0 | | **util.format(format[, ...args])** | Formats a string using the first argument as a printf-like format string | 0.5.3 | | **util.formatWithOptions(inspectOptions, format[, ...args])** | Similar to util.format(), but accepts inspect options | 10.0.0 | | **util.getSystemErrorName(err)** | Returns the system error name represented by the error code err | 9.7.0 | | **util.inherits(constructor, superConstructor)** | Inherits the prototype methods of one constructor to another (Deprecated, ES6 class and extends recommended) | 0.3.0 | | **util.inspect(object[, options])** | Returns a string representation of the object, used for debugging | 0.3.0 | | **util.isDeepStrictEqual(val1, val2)** | Tests whether two values are deeply strictly equal | 9.0.0 | | **util.promisify(original)** | Converts a callback-style function into a function returning a Promise | 8.0.0 | | **util.stripVTControlCharacters(str)** | Strips ANSI escape codes from a string | 16.11.0 | | **util.TextDecoder** | An alias for the WHATWG standard TextDecoder implementation | 8.3.0 | | **util.TextEncoder** | An alias for the WHATWG standard TextEncoder implementation | 8.3.0 | | **util.types** | Provides a utility object for various Node.js type checks | 10.0.0 | | **util.aborted(err, signal)** | Checks if the error was caused by an abort signal | 18.18.0 | | **util.parseArgs()** | Utility function for parsing command-line arguments | 18.3.0 | The `util` module in Node.js provides many practical utility functions that can help developers write code more efficiently. From type checking to asynchronous flow control, and debugging output, the `util` module covers multiple common needs in development. Although modern JavaScript already provides many native solutions, the `util` module remains very useful in many scenarios, especially when dealing with legacy code or when specific utility functions are needed.
← Nodejs Web ModuleNodejs Stream β†’