>  기사  >  웹 프론트엔드  >  Nodejs의 글로벌 모듈에 대한 심층적인 이해

Nodejs의 글로벌 모듈에 대한 심층적인 이해

黄舟
黄舟원래의
2017-06-04 10:50:162012검색

이 기사는 주로 Nodejs 글로벌 모듈에 대한 심층적인 이해를 소개합니다. 편집자는 이것이 꽤 좋다고 생각합니다. 이제 공유하고 참고하겠습니다. 편집기를 따라가서 살펴보겠습니다. 브라우저에는 자체 전역 객체

창이 있습니다. 마찬가지로 nodejs에도 자체 전역 객체 전역이 있으며, 전역 객체는 각 모듈에서 직접 액세스할 수 있습니다.

nodejs에서는 기본 JavaScript
functions

및 V8

JavaScript 엔진에서 지원하는 개체를 직접 사용하는 것 외에도 일부 다른 기능과 개체(예: 버퍼 개체, require 함수 대기)도 추가합니다.

Buffer 개체: 바이너리 데이터를 처리하는 데 사용
  1. module
  2. 개체: 현재 모듈에 대한 정보에 액세스하는 데 사용

    process 개체: 프로세스 정보에 액세스하는 데 사용
  3. console 개체: 사용되는 제어 터미널은 특정 정보를 출력합니다
  4. 6 타이머 관련 기능
  5. nodejs에서 추가한 이러한 기능과 객체는 모듈 도입 없이 바로 사용할 수 있다는 점에 유의하세요.

위 개체와 기능의 사용법은 아래에서 간략하게 설명하겠습니다.

Buffer 객체


ES6 이전에는 네이티브 JavaScript에는 바이너리 데이터를 처리하기 위한 특별한 메커니즘이 없었기 때문에 nodejs에서는 바이너리 데이터를 편리하게 처리하기 위해 Buffer 객체를 도입했습니다.

ES6 이후 네이티브 JavaScript에서는 바이너리 데이터를 처리하기 위해 Typed
Array

를 도입했습니다. TypedArray는 단일 개체로 존재하지 않고 값이 TypedArray 유형인 일련의 개체로 존재합니다. 이 일련의 객체에서 Uint8Array 객체는 Buffer 객체와 가장 유사하지만 Buffer 객체는 nodejs에 더 적합합니다.

Buffer 개체의 인스턴스는 각 요소가
integer

array와 매우 유사하지만 실제 배열과의 차이점은 크기가 고정되어 있다는 것입니다. 생성됨) 및 할당된 크기 메모리는 기본 메모리이며 V8의 힙 외부에 존재합니다. nodejs 버전 6.0 이전에는 new Buffer() 구문을 사용하여 인스턴스를 생성했습니다. 그러나 일부
보안 문제로 인해 이 형식으로 인스턴스를 생성하는 방법이 폐지되고 일부 Buffer 개체로 대체되었습니다. . 정적 방법. Create Buffer 인스턴스

Buffer.
    all
  1. oc(size[, fill[, 인코딩]]): 지정된 크기의 Buffer 인스턴스를 반환합니다. 채우기가 설정되지 않은 경우 0으로 채워집니다. default

    Buffer.allocUnsafe(size): 지정된 크기의 Buffer 인스턴스를 반환하지만 초기화되지 않으므로 민감한 데이터
  2. Buffer.allocUnsafeSlow(size)
  3. Buffer가 포함될 수 있습니다. from(array): array 값으로 초기화된 새 Buffer 인스턴스를 반환합니다(수신 배열의 요소는 숫자만 될 수 있습니다. 그렇지 않으면 자동으로 0으로 덮어쓰게 됩니다)
  4. Buffer.from(arrayBuffer[, byteOff
  5. set
  6. [, length ]]): 기본 메모리를

    복사하지 않고

    Buffer.from(buffer): 들어오는 Buffer 인스턴스의 데이터를 복사하고 새 Buffer 인스턴스를 반환
  7. 하지 않고 ArrayBuffer의 뷰를 생성합니다.
  8. Buffer.from(
  9. string
  10. [, 인코딩]): string

    const buf1 = Buffer.alloc(5);
    const buf2 = Buffer.allocUnsafe(5);
    const buf3 = Buffer.from([1, '2a', 230]);
    const buf4 = Buffer.from('abcdggg');
    console.log(buf1); // <Buffer 00 00 00 00 00>
    console.log(buf2); // <Buffer b8 ed a3 80 58> (这只是一种可能的结果)
    console.log(buf3); // <Buffer 01 00 e6>
    console.log(buf4); // <Buffer 61 62 63 64 67 67 67>
    console.log(buf4.toString()); // abcdggg
    buf2.fill(0);
    console.log(buf2); // <Buffer 00 00 00 00 00>

    값으로 초기화된 새 Buffer 인스턴스를 반환합니다. 위 내용은 명확하지 않습니다(나중에 최적화하겠습니다). 초보자이고 TypedArray가 없습니다.

하지만 걱정하지 마세요. 여러분의 허벅지는 여기 있습니다 - 노드 소스 코드 분석 – buffer

소스 코드 링크: buffer.js


문자열의 실제 바이트 길이를 반환합니다(문자 길이가 아님)

let str1 = &#39;a&#39;;
let str2 = &#39;小&#39;;
let str3 = &#39;aa&#39;;
let str4 = &#39;小a&#39;;
console.log(str1.length);    // 1
console.log(Buffer.byteLength(str1)); // 1
console.log(str2.length);    // 1
console.log(Buffer.byteLength(str2)); // 3
console.log(str3.length);    // 2
console.log(Buffer.byteLength(str3)); // 2
console.log(str4.length);    // 2
console.log(Buffer.byteLength(str4)); // 4

위의 한자는 작습니다. UTF-8 코드는 정확히 3바이트(xE5xB0x8F)를 차지하므로 위와 같은 결과가 나옵니다. Buffer.byteLength(string[, encoding]):


여러 Buffer 인스턴스 또는 Uint8Array 인스턴스를 연결하고 새 Buffer 인스턴스를 반환

const buf1 = Buffer.alloc(10);
const buf2 = Buffer.alloc(14);
const totalLength = buf1.length + buf2.length;
console.log(totalLength); // 24
const buf = Buffer.concat([buf1, buf2], totalLength);
console.log(buf.length); // 24

Buffer.concat(list[, totalLength]):객체가 Buffer 인스턴스인지 확인

Buffer.isEncoding(encoding): 判断是否支持指定的编码方式

console.log(Buffer.isEncoding(&#39;utf8&#39;)); // true
console.log(Buffer.isEncoding(&#39;utf9&#39;)); // false

Buffer.poolSize: 指定预分配的字节数的大小,默认为 8192(即 8 KB)

Buffer.prototype.buffer: 一个指向 ArrayBuffer 的引用

const arrayBuffer = new ArrayBuffer(16);
const buffer = Buffer.from(arrayBuffer);
console.log(buffer.buffer === arrayBuffer); // true

Buffer.prototype.equals(otherBuffer): 比较两个 Buffer 实例是否拥有完全相同的 bytes

const buf1 = Buffer.from(&#39;hello&#39;);
const buf2 = Buffer.from(&#39;hello&#39;);
console.log(buf1.equals(buf2)); // true

用于迭代的方法

  1. Buffer.prototype.entries()

  2. Buffer.prototype.keys()

  3. Buffer.prototype.values()

Buffer.prototype.fill(value[, offset[, <a href="http://www.php.cn/wiki/1048.html" target="_blank">end</a>]][, encoding]): 用指定的值填充满 Buffer 实例

const b = Buffer.allocUnsafe(25).fill(&#39;abc呵呵&#39;);
// 注意下面因为不够容纳全部的汉字字节,所以乱码
console.log(b.toString()); // abc呵呵abc呵呵abc呵�

Buffer.prototype.<a href="http://www.php.cn/wiki/137.html" target="_blank">include</a>s(value[, byteOffset][, encoding])

Buffer.prototype.indexOf(value[, byteOffset][, encoding])

Buffer.prototype.to<a href="http://www.php.cn/wiki/1488.html" target="_blank">JSON</a>(): 返回一个 JSON 对象

当 JSON.stringify(buf) 的参数为一个 Buffer 实例时,会隐式地调用上面的方法

const b = Buffer.from(&#39;hell&#39;)
let json = b.toJSON();
console.log(json); // { type: &#39;Buffer&#39;, data: [ 104, 101, 108, 108 ] }
console.log(JSON.stringify(b)); // {"type":"Buffer","data":[104,101,108,108]}

Buffer.prototype.toString([encoding[, start[, end]]]): 以指定的 encoding 解码 Buffer 实例,返回解码后的字符串

const buf = Buffer.from([104, 101, 108, 108]);
console.log(buf.toString()); // hell
console.log(buf.toString(&#39;base64&#39;)); // aGVsbA==
console.log(buf.toString(&#39;hex&#39;)); // 68656c6c

字符串不能被修改,但是 Buffer 实例却可以被修改。

const buf = Buffer.from(&#39;abcd&#39;);
console.log(buf.toString()); // abcd
buf[1] = 122;
console.log(buf.toString()); // azcd

Buffer.prototype.write(string[, offset[, length]][, encoding]): 将指定字符串写入到 Buffer 中

const buf = Buffer.from(&#39;abcdefg&#39;);
console.log(buf); // <Buffer 61 62 63 64 65 66 67>
console.log(buf.toString()); // abcdefg
buf.write(&#39;和&#39;, 1);
console.log(buf); // <Buffer 61 e5 92 8c 65 66 67>
console.log(buf.toString()); // a和efg

好了,还有一堆方法就不一一列出来了,Buffer 就到这里了。

module 对象

在使用 require 函数加载模块文件时,将运行该模块文件中的每一行代码

模块在首次加载后将缓存在内存缓存区中,所以对于相同模块的多次引用得到的都是同一个模块对象,即对于相同模块的多次引用不会引起该模块内代码的多次执行。

在编译的过程中,Node 会对获取的 JavaScript 文件内容进行头尾包装!

// 包装前 module666.js
const PI = 6666;
module.exports = PI;
// 包装后,注意下面不是立即执行函数
(function(exports, require, module, filename, dirname) {
 const PI = 6666;
 module.exports = PI;
});

filename & dirname

  1. filename: 返回当前模块文件的绝对路径(带文件名)

  2. dirname: 返回当前模块文件所在目录的绝对路径

// 1.js
console.log(filename); // c:\Users\percy\Desktop\nodejs\1.js
console.log(dirname); // c:\Users\percy\Desktop\nodejs

Process 对象

process 对象是 nodejs 的一个全局对象,提供当前 nodejs 进程的信息。

属性

  1. process.arch: 返回当前处理器的架构

  2. process.env: 返回一个包含用户环境变量的对象

  3. process.argv: 返回一个数组,数组的第一个元素总是 node 程序的绝对路径,第二个元素是当前执行脚本的绝对路径

  4. process.execPath: 返回 node 程序的绝对路径

  5. process.argv0: 返回 node 程序的绝对路径

  6. process.pid: 返回当前进程的进程号

  7. process.platform: 返回当前的系统平台标识符(比如:'darwin', ‘freebsd', ‘linux', ‘sunos' or ‘win32')

  8. process.version: 返回当前 node 的版本号

  9. process.versions: 返回一个对象,列出了 nodejs 和其相关依赖的版本号

三个重要的属性

  1. process.stdin: 返回一个指向标准输入流的可读流(Readable Stream)

  2. process.stdout: 返回一个指向标准输出流的可写流(Writable Stream)

  3. process.stderr: 返回一个指向标准错误流的可写流(Writable Stream)

方法

  1. process.cwd(): 返回进程当前的工作目录

  2. process.chdir(path): 改变进程当前的工作目录

  3. process.cpuUsage(): 返回当前 CPU 的使用情况

  4. process.memoryUsage(): 返回当前内存的使用情况

  5. process.uptime(): 返回 Node 程序已运行的秒数

  6. process.nextTick(callback[, …args]): 指定回调函数在当前执行栈的尾部、下一次Event Loop之前执行

  7. process.emitWarning(warning[, options]): 触发一个 warning 事件,可以自定义一些警告信息

  8. process.exit([code]): 立即结束当前进程,但是会触发 process 的 exit 事件

  9. process.abort(): 立即结束当前进程,不会触发 exit 事件

console.log(process.cwd()); // c:\Users\percy\Desktop\nodejs
process.chdir(&#39;../&#39;);
console.log(process.cwd()); // c:\Users\percy\Desktop
process.emitWarning(&#39;Something happened!&#39;, {
 code: &#39;MY_WARNING&#39;,
 detail: &#39;This is some additional information&#39;
});
process.on(&#39;warning&#39;, (warning) => {
 console.log(warning);
})
process.on(&#39;exit&#39;, function(code) {
 console.log(&#39;exit~&#39;, code);
});
process.exit(); // exit~

process 对象还有一些方法没列出来,因为我现在看不懂怎么用,以后补 >_<

Console 对象

这个对象就是用来在控制台下面打印一些信息而已,挑几个有用但没记牢的方法来玩玩。

console.dir(value): 打印一个对象的详细信息

const buf = Buffer.from(&#39;abcdefg&#39;);
console.log(buf); // <Buffer 61 62 63 64 65 66 67>
console.dir(buf); // Buffer [ 97, 98, 99, 100, 101, 102, 103 ]

console.time(label) & console.timeEnd(label): 用来统计代码执行时间

let label = &#39;time&#39;;
let str = &#39;hello&#39;;
console.time(label);
while (str.length < 999999) {
 str += &#39;a&#39;;
}
console.timeEnd(label); // time: 133.724ms

6 个计时器函数

在浏览器上,就有相应的 4 个计时器函数(setInterval、clearInterval、setTimeout、clearTimeout),只不过它们是 window 全局对象的属性。

在 nodejs 中,除过上面的 4 个计时器,还增加了两个(setImmediate,clearImmediate)。

这六个计时器函数被定义在了全局对象 global 下,即可以直接在代码中进行使用。


위 내용은 Nodejs의 글로벌 모듈에 대한 심층적인 이해의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.