search
HomeWeb Front-endJS TutorialA detailed introduction to global objects in 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

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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools