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

A detailed introduction to global objects in Node.js

不言
不言Original
2018-08-23 17:16:252217browse

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

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

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

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("炮兵团");

//输出
团
    一营
        一连
        二连
    二营
        一连
        二连
炮兵团

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);
})

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立即执行

(2)取消定时

        clearTimeout(timeout)

        clearInterval(timeout)

         clerImmediate(Immediate)

例子:

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

四: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);

(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

例子二:

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

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));
    }
})

(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

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

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

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

isBuffer()  ---

isEncoding() ---

PoolSize属性

ToString() ---buffer输出

例子:综合以上例子

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

(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:
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