最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Node.js API詳解之 util模塊用法實例分析

 更新時間:2020年05月09日 08:41:44   作者:李小強  
這篇文章主要介紹了Node.js API詳解之 util模塊用法,結(jié)合實例形式分析了node.js API中util模塊基本功能與相關(guān)函數(shù)使用技巧,需要的朋友可以參考下

本文實例講述了Node.js API詳解之 util模塊用法。分享給大家供大家參考,具體如下:

Node.js API詳解之 util

util 模塊主要用于支持 Node.js 內(nèi)部 API 的需求。提供了大部分實用工具。
通過 const util = require(‘util'); 的方式引用util模塊

util.callbackify(original)

說明:

original:傳遞一個 async 函數(shù),或者是一個返回Promise的異步函數(shù)。
callbackify會返回一個方法,執(zhí)行該方法時傳遞一個回調(diào)函數(shù),回調(diào)函數(shù)的第一個參數(shù)是err,第二個是異步函數(shù)的返回值。

demo:

const util = require('util');
async function fn() {
 return await Promise.resolve('hello isjs');
}
const callbackFunction = util.callbackify(fn);
callbackFunction((err, ret) => {
 if (err) throw err;
 console.log(ret);
});
//輸出: hello isjs

util.debuglog(section)

說明:

util.debuglog() 方法用于創(chuàng)建一個函數(shù),基于 NODE_DEBUG 環(huán)境變量的存在與否有條件地寫入調(diào)試信息到 stderr。
如果 section 名稱在環(huán)境變量的值中,則返回的函數(shù)類似于 console.error()。 否則,返回的函數(shù)是一個空操作。
section:一個字符串,指定要為應用的哪些部分創(chuàng)建 debuglog 函數(shù)。

demo:

const util = require('util');
const debuglog = util.debuglog('foo');
debuglog('hello from foo [%d]', 123);

util.deprecate(function, string)

說明:

該方法會包裝給定的 function 或類,并標記為廢棄的。

demo:

const util = require('util');
function isBoolean(obj){
 return (obj === true || obj === false);
}
isBoolean = util.deprecate(isBoolean, 'isBoolean 方法已被廢棄');
isBoolean(true);
//輸出:(node:9911) DeprecationWarning: isBoolean 方法已被廢棄

util.format(format[, …args])

說明:

util.format() 方法返回一個格式化后的字符串,
format:第一個參數(shù)是一個字符串,包含零個或多個占位符。
每個占位符會被對應參數(shù)轉(zhuǎn)換后的值所替換。 支持的占位符有:
%s:字符串
%d:數(shù)值(整數(shù)或浮點數(shù))
%i:整數(shù)
%f:浮點數(shù)
%j – JSON
%o – Object(包括不可枚舉的屬性方法)
%O – Object(不包括不可枚舉屬性)
%% – 單個百分號('%')不消耗參數(shù)。

demo:

const util = require('util');
var formatString = util.format('%s %d %i %f %j', 'hello', 1.123, 123, 2.1, "{'name': 'xiao', 'age': '18'}");
console.log(formatString);
//e輸出: hello 1.123 123 2.1 "{'name': 'xiao', 'age': '18'}"
//如果占位符沒有對應的參數(shù),則占位符不被替換。
formatString = util.format('%s , %s', 'hello');
console.log(formatString);
//輸出: hello , %s
//如果傳入的參數(shù)比占位符的數(shù)量多,則多出的參數(shù)會被強制轉(zhuǎn)換為字符串,
//然后拼接到返回的字符串,參數(shù)之間用一個空格分隔。
formatString = util.format('%s , %s', 'hello', 'isjs', '!');
console.log(formatString);
//輸出: hello , isjs !
//如果第一個參數(shù)不是一個字符串,則返回一個所有參數(shù)用空格分隔并連在一起的字符串
formatString = util.format(1, 2, 3);
console.log(formatString);
//輸出: 1 2 3
//如果只傳入占位符而不傳入?yún)?shù),則原樣返回
formatString = util.format('%% , %s');
console.log(formatString);
//輸出: %% , %s

util.inherits(constructor, superConstructor)

說明:

注意,不建議使用 util.inherits()。 請使用 ES6 的 class 和 extends 關(guān)鍵詞獲得語言層面的繼承支持。
從一個構(gòu)造函數(shù)中繼承原型方法到另一個。
constructor 的 prototype 會被設置到一個從 superConstructor 創(chuàng)建的新對象上。
superConstructor 可通過 constructor.super_ 屬性訪問

demo:

const util = require('util');
const EventEmitter = require('events');
function MyStream() { 
 EventEmitter.call(this);
}
util.inherits(MyStream, EventEmitter);
MyStream.prototype.write = function(data) {
 this.emit('data', data);
};
const stream = new MyStream();
console.log(stream instanceof EventEmitter); // true
console.log(MyStream.super_ === EventEmitter); // true
stream.on('data', (data) => {
 console.log(`接收的數(shù)據(jù):"${data}"`);
});
stream.write('運作良好!'); // 接收的數(shù)據(jù):"運作良好!"
//建議使用 ES6 的 class 和 extends:
const EventEmitter = require('events');
class MyStream extends EventEmitter {
 write(data) {
 this.emit('data', data);
 }
}
const stream = new MyStream();
stream.on('data', (data) => {
 console.log(`接收的數(shù)據(jù):"${data}"`);
});
stream.write('使用 ES6');

util.inspect(object[, options])

說明:

方法返回 object 的字符串表示,主要用于調(diào)試。
object: 任何 JavaScript 原始值或?qū)ο?br /> options: 可用于改變格式化字符串的某些方面。

demo:

const util = require('util');
const inspectOpt = {
 showHidden: false,//如果為 true,則 object 的不可枚舉的符號與屬性也會被包括在格式化后的結(jié)果中。
 depth: 2,//指定格式化 object 時遞歸的次數(shù)。 默認為 2。 若要無限地遞歸則傳入 null。
 colors: false,//如果為 true,則輸出樣式使用 ANSI 顏色代碼。 默認為 false。
 customInspect: true,//如果為 false,則 object 上自定義的 inspect(depth, opts) 函數(shù)不會被調(diào)用。 默認為 true
 showProxy: false,//如果為 true,則 Proxy 對象的對象和函數(shù)會展示它們的 target 和 handler 對象。 默認為 false
 maxArrayLength: 100,//指定格式化時數(shù)組和 TypedArray 元素能包含的最大數(shù)量。 默認為 100。 設為 null 則顯式全部數(shù)組元素。 設為 0 或負數(shù)則不顯式數(shù)組元素。
 breakLength: 60//一個對象的鍵被拆分成多行的長度。 設為 Infinity 則格式化一個對象為單行。 默認為 60。
};
console.log(util.inspect(util, inspectOpt));

util.inspect.styles, util.inspect.colors

說明:

可以通過 util.inspect.styles 和 util.inspect.colors 屬性全局地自定義 util.inspect 的顏色輸出(如果已啟用)。
預定義的顏色代碼有:white、grey、black、blue、cyan、green、magenta、red 和 yellow。
還有 bold、italic、underline 和 inverse 代碼。
顏色樣式使用 ANSI 控制碼,可能不是所有終端都支持。

demo:

const util = require('util');
console.log(util.inspect.styles);
// { special: 'cyan',
// number: 'yellow',
// boolean: 'yellow',
// undefined: 'grey',
// null: 'bold',
// string: 'green',
// symbol: 'green',
// date: 'magenta',
// regexp: 'red' }
console.log(util.inspect.colors);
// { bold: [ 1, 22 ],
// italic: [ 3, 23 ],
// underline: [ 4, 24 ],
// inverse: [ 7, 27 ],
// white: [ 37, 39 ],
// grey: [ 90, 39 ],
// black: [ 30, 39 ],
// blue: [ 34, 39 ],
// cyan: [ 36, 39 ],
// green: [ 32, 39 ],
// magenta: [ 35, 39 ],
// red: [ 31, 39 ],
// yellow: [ 33, 39 ] }

util.inspect.custom

說明:

util.inspect.custom是一個符號,可被用于聲明自定義的查看函數(shù):[util.inspect.custom](depth, opts)
自定義 inspect 方法的返回值可以使任何類型的值,它會被 util.inspect() 格式化。

demo:

const util = require('util');
class Box {
 [util.inspect.custom](depth, options) {
 return "myInspect";
 }
}
const box = new Box();
console.log(util.inspect(box));
// 輸出:myInspect
 

util.inspect.defaultOptions

說明:

defaultOptions 值允許對 util.inspect 使用的默認選項進行自定義。
它需被設為一個對象,包含一個或多個有效的 util.inspect() 選項。 也支持直接設置選項的屬性。

demo:

const util = require('util');
util.inspect.defaultOptions = {
 showHidden: true,
 depth:3
};
util.inspect.defaultOptions.breakLength = 30;
console.log(util.inspect.defaultOptions);
// { showHidden: true,
// depth: 3,
// colors: false,
// customInspect: true,
// showProxy: false,
// maxArrayLength: 100,
// breakLength: 30 }

util.promisify(original)

說明:

讓一個遵循通常的 Node.js error first回調(diào)風格的函數(shù),回調(diào)函數(shù)是最后一個參數(shù), 返回一個返回值是一個 promise 版本的函數(shù)。

demo:

const util = require('util');
const fs = require('fs');
const stat = util.promisify(fs.stat);
stat('.').then((stats) => {
 // Do something with `stats`
}).catch((error) => {
 // Handle the error.
});

util.promisify.custom

說明:

使用util.promisify.custom符號可以自定義promisified功能。

demo:

const util = require('util');
function doSomething(foo, callback) {
 // ...
}
doSomething[util.promisify.custom] = function(foo) {
 return getPromiseSomehow();
};
const promisified = util.promisify(doSomething);
console.log(promisified === doSomething[util.promisify.custom]);
// 輸出: true

類:util.TextEncoder

說明:

該類用來對文本進行編碼

textEncoder.encode([input])

說明:

對input字符串進行編碼并返回一個Uint8Array包含編碼字節(jié)的字符串

textEncoder.encoding

說明:

TextEncoder實例支持的編碼??偸窃O置為'utf-8'。

demo:

const encoder = new TextEncoder();
const uint8array = encoder.encode('this is some data');
console.log(encoder.encoding)
//utf-8

類:util.TextDecoder

說明:

該類用來解析編碼后的文本

new TextDecoder([encoding[, options]])

說明:

創(chuàng)建一個TextDecoder實例。
encoding: 編碼方式,默認'utf-8′
options: 選項
fatal: 解碼發(fā)生的錯誤將導致 TypeError被拋出。默認為 false
ignoreBOM: 解碼結(jié)果中是否會包含字節(jié)順序標記。默認為false。僅當encoding的值為'utf-8','utf-16be'或'utf-16le'時有效。

textDecoder.decode([input[, options]])

說明:

解碼input并返回一個字符串。
input: 待解碼數(shù)據(jù)
options.stream: 如果需要額外的數(shù)據(jù)塊,設置為true。默認為false。

textDecoder.encoding

說明:

返回textDecoder實例支持的編碼。

textDecoder.fatal

說明:

返回textDecoder實例的fatal屬性,

textDecoder.ignoreBOM

說明:

返回解碼結(jié)果是否包含字節(jié)順序標記

希望本文所述對大家node.js程序設計有所幫助。

相關(guān)文章

  • nodejs接入阿里大魚短信驗證碼的方法

    nodejs接入阿里大魚短信驗證碼的方法

    本篇文章主要介紹了nodejs接入阿里大魚短信驗證碼的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下。
    2017-07-07
  • node.js中的fs.fchmod方法使用說明

    node.js中的fs.fchmod方法使用說明

    這篇文章主要介紹了node.js中的fs.fchmod方法使用說明,本文介紹了fs.fchmod的方法說明、語法、接收參數(shù)、使用實例和實現(xiàn)源碼,需要的朋友可以參考下
    2014-12-12
  • Node中的util.promisify()方法的基本使用和實現(xiàn)

    Node中的util.promisify()方法的基本使用和實現(xiàn)

    眾所周知,在JS中實現(xiàn)異步編程主要是通過以下幾種方案,回調(diào)函數(shù),觀察者模式,Generator,Promise,async / await ,今天就和大家一起聊一下在node中的一個util.promisify()這個API的基本使用和基本實現(xiàn)
    2023-07-07
  • 詳解Node.js服務器靜態(tài)資源處理

    詳解Node.js服務器靜態(tài)資源處理

    靜態(tài)資源服務器指的是不會被服務器的動態(tài)運行所改變或者生成的文件,本文主要為大家詳細介紹了Node.js服務器靜態(tài)資源處理的相關(guān)知識,需要的可以了解下
    2024-04-04
  • node.js自動上傳ftp的腳本分享

    node.js自動上傳ftp的腳本分享

    這篇文章主要給大家介紹了一個關(guān)于node.js自動上傳ftp腳本的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面隨著小編來一起學習學習吧
    2018-06-06
  • node.js中的fs.appendFileSync方法使用說明

    node.js中的fs.appendFileSync方法使用說明

    這篇文章主要介紹了node.js中的fs.appendFileSync方法使用說明,本文介紹了fs.appendFileSync方法說明、語法、接收參數(shù)、使用實例和實現(xiàn)源碼,需要的朋友可以參考下
    2014-12-12
  • 提高Node.js性能的應用技巧分享

    提高Node.js性能的應用技巧分享

    Node.js 是單線程非阻塞 I/O, 使其可以支持成千上萬的并發(fā)操作。這和 NGINX 解決 C10K 問題的方式如出一轍。Node.js 以高效的性能和開發(fā)效率著稱。
    2017-08-08
  • Node.js中的不安全跳轉(zhuǎn)如何防御詳解

    Node.js中的不安全跳轉(zhuǎn)如何防御詳解

    安全是不容忽視的,每個開發(fā)者都知道它非常重要,真正嚴肅對待它的卻沒有幾人。下面這篇文章主要給大家介紹了關(guān)于Node.js中不安全跳轉(zhuǎn)如何防御的相關(guān)資料,文中通過示例代碼介紹的非常詳細。需要的朋友可以參考下
    2018-10-10
  • nodejs 提示‘xxx’ 不是內(nèi)部或外部命令解決方法

    nodejs 提示‘xxx’ 不是內(nèi)部或外部命令解決方法

    本文介紹了node.js包管理工具npm安裝模塊后,無法通過命令行執(zhí)行命令,提示‘xxx’ 不是內(nèi)部或外部命令的解決方法,給需要的小伙伴參考下。
    2014-11-11
  • nodejs個人博客開發(fā)第七步?后臺登陸

    nodejs個人博客開發(fā)第七步?后臺登陸

    這篇文章主要為大家詳細介紹了nodejs個人博客開發(fā)的后臺登陸功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-04-04

最新評論

化州市| 海门市| 洪湖市| 伽师县| 祁阳县| 瑞昌市| 沂水县| 松原市| 徐州市| 若尔盖县| 洞口县| 宿州市| 穆棱市| 浑源县| 仁化县| 河源市| 来宾市| 庄河市| 闵行区| 凌源市| 增城市| 西贡区| 凤台县| 肇东市| 墨脱县| 繁昌县| 石台县| 盐池县| 武穴市| 偏关县| 双峰县| 陵水| 汤原县| 宝鸡市| 阆中市| 滁州市| 罗甸县| 潞城市| 肃宁县| 嘉善县| 咸宁市|