Home Web Front-end JS Tutorial A detailed introduction to global objects in Node.js

A detailed introduction to global objects in Node.js

Aug 23, 2018 pm 05:16 PM
node.js

This article brings you a detailed introduction to global objects in Node.js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1: Path of Node global object

1. Path

_filename ---Current file path

_dirname ----The directory where the current file is located

Example:

console.log(__filename);
console.log(__dirname);
输出结果:
/Users/macshiguang/node/npm2/index.js
/Users/macshiguang/node/npm2
Copy after login

2: Node global object console

2.console (console)

(1) Placeholder

%s ----String

console.log("hello %s world","world"); //Output: hello world world

%d ---Value (integer or floating point number)

console.log("Price: %d","88"); //Output: Price: 88

%i ----Integer, integer

console.log("%i",300.8); // Output 300

%f ----Floating point value, floating point type

console.log("%f",200.3); //Output 200.3

%j ----JSON, if the parameter contains a circular reference, replace

console with the string '[Circular]'. log('json:%j',{name:'zhang'}); //json:{"name":"zhang"}

console.log({name:'zhang'}); //Output object: { name: 'zhang' }

(2) console object attribute

log() ---Log

count() ---Count

 console.count();
console.count('tag'); // default: 1   tag: 1

console.count();
console.count('tag'); // default: 2   tag: 2

console.count();
console.count('tag');// default: 3   tag: 3
Copy after login

countRe set() ---Reset count

console.countReset('tag');

console.count('tag'); //Connect the above count , tag: 1

dir() ---Output attributes and methods

// Output a certain parameter

console.dir(global);

//Output an attribute in the parameter

console.log(global,{colors:true})

//Output the The first level of the attribute, depth, how many times to recurse when formatting the object

console.dir(global,{colors:true,depth:1});

time() ---Calculate the running time of a program

timeEnd() ---Calculate the running time of a program

// 时间
console.time();
for (let i = 0;i<1000;i++){
     i * 15 +120 /34;
}
console.timeEnd();//undefined: 0.054ms
Copy after login

group() ---Increase the indentation of subsequent lines by two spaces

groupEnd() ---Delete two spaces from the indentation of subsequent lines

console.log("团");
console.group();
console.log("一营");
console.group();
console.log("一连");
console.log("二连");
console.groupEnd();
console.log("二营");
console.group();
console.log("一连");
console.log("二连");
console.groupEnd();
console.groupEnd();
console.log("炮兵团");

//输出
团
    一营
        一连
        二连
    二营
        一连
        二连
炮兵团
Copy after login

error() ---Error

console .error("Error");

##warn() ---Warning

console.warn("Warning");

trace ---Debug information

console.trace ("trace");

(3)Character drawing

figlet package

Installation:

npm install figlet

Introduction:

figlet("hello world !",function (err,data) {
    console.log(data);
})
Copy after login

3. Node global object timer

3、定时器

(1)设置定时

setTimeout(callback , delay[ , args......])

setInterval(callback, delay[ , args......])

setImmediate(callback, [ , args......]) ---异步执行

例子:

// 定时器,异步执行(先同步后异步)
let myImmediate = setImmediate(function () {
    console.log("setImmediate立即执行");
})

//同步执行
setTimeout(function (name) {
    console.log("setTimeout");
})

//输出结果
setTimeout
setImmediate立即执行
Copy after login

(2)取消定时

clearTimeout(timeout)

clearInterval(timeout)

clerImmediate(Immediate)

例子:

let myImmediate = setImmediate(function () {
    console.log("setImmediate立即执行");
})
clearImmediate(myImmediate);
Copy after login

四:Node全局对象之Module

4、Module(模块)

属性:

exports ---模块中导入的方法,属性,类, module.exports===exports,改变属性值用:module.exports

require() ---引入模块module.require() ===require()

require.main ---得到直接使用node运行的模块,require.main === module

parent ---父模块

children ---子模块

filename ---当前模块的路径,等同于__filename

id ---

loaded ---

paths ---

五. Node全局对象之process

5. Process(进程)

(1)对象属性

pid ---进程号

title ---进程名

argv ---命令行选项组成的数组

argv0 ---命令行选项的第一个

env ---环境信息

execPath ---node.exe的路径

arch ---CPU架构

versions ---版本号信息

platform ---平台信息/操作系统信息

cwd() --返回进程工作目录(当前运行文件的目录)

memoryUsage() --返回内存使用情况,单位byte

exit() ---结束进程

例子:www/test-01.js

console.log(process.pid);//13196
console.log(process.title);//D:\WebStorm\WebStorm 2017.2\bin\runnerw.exe
console.log(process.argv);//[ &#39;D:\\nodejs\\node.exe&#39;, &#39;D:\\nodejs\\www\\test\\test-01.js&#39; ]
console.log(process.argv0);//D:\nodejs\node.exe
console.log(process.cwd());//D:\nodejs\www\test
//开启异步操作
setTimeout(function () {
},100000);
Copy after login

(2)输入输出流(I/O)

process.stdin ---输入

process.stdout ---输出

例子一:

// 输出流
process.stdout.write("hello");
process.stdout.write(",world");

// 输入流
process.stdin.on(&#39;data&#39;,function (name) {
    console.log(&#39;请输入用户名:&#39;+name);
})

//输出:
hello,world
请输入用户名:
zhang
请输入用户名:zhang
Copy after login

例子二:

输入任意两个数,自动计算其和

let a;
let b;
process.stdout.write("请输入a的值:");
process.stdin.on(&#39;data&#39;,function (chunk) {
    if(!a){
        a=Number(chunk);
        process.stdout.write("请输入b的值:");
    }else {
        b=Number(chunk);
        process.stdout.write("a+b的和为:"+(a + b));
    }
})
Copy after login

(3)Exit Codes

  1. 正常情况下,无异步操作正在等待,node.js以状态码0退出


  2. 未捕捉异常......

详情:http://nodejs.cn/api/process.html#process_exit_codes

六. Node全局对象之Buffer

6. Buffer

(1) 什么是Buffer

读取或者操作二进制数据流

Buffer类的实例类似整数数组,但Buffer的大小是固定的且在V8堆外分配物理内存。

使用Buffer来存储需要占用大量内存的数据

(2)Buffer的应用

读取文件内容时,返回是buffer

使用net或者http模块来接受网络数据时,data事件的参数也是一个buffer

使用node.js编写一些底层功能时,比如:网络通信模块,某个数据库的客户端模块,或需从文 件中操作大量结构化数据时

(3)类方法

Buffer.alloc() ---分配长度,每个元素自动填充0,每个元素都是一个字节byte(8bit)

通过在http://tool.oschina.net/hexconvert中查看进制转换

例子:

// 创建buffer
// 为Buffer对象分配10个长度,每个元素自动填充0
//buffer的每个元素都是一个字节byte(8bit)
const buf = Buffer.alloc(10);
buf[0] =10;
buf[1] =250;//转为10进制为fa
buf[2] =300;//转为10进制为2c
console.log(buf);//<Buffer 0a fa 2c 00 00 00 00 00 00 00>
console.log(buf.length);//10
Copy after login

Buffer.from() ---快速创建Buffer

例子:

// 快速创建
// 数组
const buf2 = Buffer.from([1,2,260,4]);
console.log(buf2);//<Buffer 01 02 04 04>
console.log(buf2.length);//4
// 字符串,需utf-8编码
const buf3  =Buffer.from(&#39;你好&#39;,&#39;utf8&#39;);
console.log(buf3);//<Buffer e4 bd a0 e5 a5 bd>
console.log(buf3.length);//6
Copy after login

Buffer.allocUnSafe() ---创建Buffer

例子:

// 直接从内存开辟空间,10个字节,没有初始化
const buf4 = Buffer.allocUnsafe(10);
console.log(buf4);//输出有内容,<Buffer 98 21 49 7e bf 02 00 00 08 22>,
// 直接从内存开辟空间,10个字节,没有初始化(可能回保存好旧的数据)速度比较快
buf4.fill(&#39;a&#39;);//每一个填充a
console.log(buf4.length);//4
Copy after login

Buffer.allocUnSafeSlow() --

Buffer.byteLength() ---

Buffer.compare() ---

Buffer.concat() ---拼接buffer

例子:综和上面创建的buffer:

//拼接buffer
const buf5 = Buffer.concat([buf,buf2]);
console.log(buf5);//<Buffer 0a fa 2c 00 00 00 00 00 00 00 01 02 04 04>
console.log(buf5.length);//14
Copy after login

isBuffer() ---

isEncoding() ---

PoolSize属性

ToString() ---buffer输出

例子:综合以上例子

// buffer 输出字符串
console.log(buf.toString(&#39;hex&#39;));//
console.log(buf3.toString(&#39;utf8&#39;));//你好
Copy after login

(4) Buffer对象方法

      Buf[index]

      Buf.buffer

      Buf.compare()

      Buf.copy()......

      详情见:http://nodejs.cn/api/buffer.html

相关推荐:


The above is the detailed content of A detailed introduction to global objects in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Let's talk about how to choose the best Node.js Docker image? Let's talk about how to choose the best Node.js Docker image? Dec 13, 2022 pm 08:00 PM

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

Node.js 19 is officially released, let's talk about its 6 major features! Node.js 19 is officially released, let's talk about its 6 major features! Nov 16, 2022 pm 08:34 PM

Node 19 has been officially released. This article will give you a detailed explanation of the 6 major features of Node.js 19. I hope it will be helpful to you!

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

Let's talk about the event loop in Node Let's talk about the event loop in Node Apr 11, 2023 pm 07:08 PM

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

Let's talk about the GC (garbage collection) mechanism in Node.js Let's talk about the GC (garbage collection) mechanism in Node.js Nov 29, 2022 pm 08:44 PM

How does Node.js do GC (garbage collection)? The following article will take you through it.

Learn more about Buffers in Node Learn more about Buffers in Node Apr 25, 2023 pm 07:49 PM

At the beginning, JS only ran on the browser side. It was easy to process Unicode-encoded strings, but it was difficult to process binary and non-Unicode-encoded strings. And binary is the lowest level data format of the computer, video/audio/program/network package

See all articles