在上一篇的结尾,我留下了一个疑问,就是我们在几个脚本块中都用到了把字节转化为base64字符串的一个方法。当时的写法是,每次都引用一段代码。.
function convertToBase64(input: ArrayBuffer) {
const uInt8Array = new Uint8Array(input);
const count = uInt8Array.length;
// Allocate the necessary space up front.
const charCodeArray = new Array(count) as string[];
// Convert every entry in the array to a character.
for (let i = count; i >= 0; i--) {
charCodeArray[i] = String.fromCharCode(uInt8Array[i]);
}
// Convert the characters to base64.
const base64 = btoa(charCodeArray.join(""));
return base64;
}
如果一次这么写,是没有问题的。但如果每次都这么写,就不太好了。实际上作为程序员,最经常会用到的一个技巧就是封装重用。你自然会想到,有没有可能去引用一个已经写好的模块来解决这个问题呢。
答案当然是可以的,我也很快找到了一个合适的模块(base64-js:https://www.npmjs.com/package/base64-js),并且在scriptlab中添加了它的引用。
需要注意的是,通常这里直接写模块名称,和类型定义名称就可以了。但有些时候,某些模块编写的不太规范,可能就需要写上js文件路径,以及类型定义名称了。
如此一来,我们的功能代码就简单了。请注意看下面被选中的这一行代码。
掌握了这个技巧,你就可以利用在npmjs.com中的数以百万计的项目,做你任何想做的事情,你当然也可以贡献你的模块,造福更多人。