字符串编解码
说明: 从 API Version 7 开始支持。
导入模块
import util from '@ohos.util'
权限
无
util.printf
printf(format: string, ...args: Object[]): string
通过式样化字符串对输入的内容按特定格式输出。
-
参数:
-
返回值:
-
示例:
var res = util.printf("%s", "hello world!"); console.log(res);
util.getErrorString
getErrorString(errno: number): string
获取系统错误码对应的详细信息。
-
参数:
-
返回值:
-
示例:
var errnum = 10; // 10:a system error number var result = util.getErrorString(errnum); console.log("result = " + result);
util.callbackWrapper
callbackWrapper(original: Function): (err: Object, value: Object)=>void
对异步函数进行回调化处理,回调中第一个参数将是拒绝原因(如果 Promise 已解决,则为 null),第二个参数将是已解决的值。
-
参数:
-
返回值:
-
示例:
async function promiseFn() { return Promise.reject('value'); } var cb = util.callbackWrapper(promiseFn); cb((err, ret) => { expect(err).strictEqual('value'); expect(ret).strictEqual(undefined); })
util.promiseWrapper
promiseWrapper(original: (err: Object, value: Object) => void): Object
对异步函数处理并返回一个promise的版本。
-
参数:
-
返回值:
采用遵循常见的错误优先的回调风格的函数(也就是将 (err, value) => ... 回调作为最后一个参数),并返回一个返回 promise 的版本。
-
示例:
function aysnFun(str1, str2, callback) { if (typeof str1 === 'string' && typeof str1 === 'string') { callback(null, str1 + str2); } else { callback('type err'); } } let newPromiseObj = util.promiseWrapper(aysnFun)("Hello", 'World'); newPromiseObj.then(res => { expect(res).strictEqual('HelloWorld'); })
TextDecoder
属性
constructor
constructor(encoding?: string, options?: { fatal?: boolean; ignoreBOM?: boolean },)
TextDecoder的构造函数。
-
参数:
表 1 options
-
示例:
var textDecoder = util.TextDecoder("utf-8",{ignoreBOM:true})
decode
decode(input: Uint8Array, options?:{stream?:false}): string
通过输入参数解码后输出对应文本。
-
参数:
表 2 options
在随后的decode()调用中是否跟随附加数据。如果以块的形式处理数据,则设置为true;如果处理最后的块或数据未分块,则设置为false。默认为false。
-
返回值:
-
示例:
var textDecoder = util.TextDecoder("utf-8",{ignoreBOM:true}); var result = new Uint8Array(6); result[0] = 0xEF; result[1] = 0xBB; result[2] = 0xBF; result[3] = 0x61; result[4] = 0x62; result[5] = 0x63; console.log("input num:"); for(var j= 0; j < 6; j++) { console.log(result[j]); } var retStr = textDecoder.decode( result , {stream:false}); console.log("retStr = " + retStr);
TextEncoder
属性
constructor
constructor()
TextEncoder的构造函数。
-
示例:
var textEncoder = new util.TextEncoder()
encode
encode(input?: string): Uint8Array
通过输入参数编码后输出对应文本。
-
参数:
-
返回值:
-
示例:
var textEncoder = new util.TextEncoder() var result = new Uint8Array(buffer); result = textEncoder.encode("\uD800¥¥");
encodeInto
encodeInto(input: string, dest: Uint8Array,):{ read: number; written: number }
放置生成的UTF-8编码文本。