如何使用TypeScript以编程方式确定一串代码中有多少千字节?

时间:2019-05-02 17:51:55

标签: javascript string typescript file size

假设我有以下TypeScript代码(以字符串表示):

function greet(name: string): void {
  console.log(`Hello ${name}!`);
}

我如何以编程方式确定此字符串中有多少千字节?

我当前正在使用以下公式:

// NOTE: "string.length" represents the number of bytes in the string
const KB: number = (string.length / 1024).toFixed(2);

问题在于该数字经常看起来太大或太小而无法正确计算。

当我将字符串放在一个空文件中并保存时,我的文件管理器的属性输出的大小会完全不同,有时会有2-20 KB的大小。

我在做什么错了,我应该使用1000个字节代表一个千字节而不是1024吗?

有什么我不能正确理解的东西吗?

1 个答案:

答案 0 :(得分:2)

JavaScript字符串中的字符使用Unicode进行编码,每个引擎都有自己的字符集,最受欢迎的是UTF-16。因此,每个字符都保存2 bytes数据。要查找字符串使用的总数kilobytes,请找到使用的bytes数并将其除以1024

const string = "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc";

const b = string.length * 2;
const kb = (b / 1024).toFixed(2);

console.log(`${kb}KB`);