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 drawingfiglet 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);//[ 'D:\\nodejs\\node.exe', 'D:\\nodejs\\www\\test\\test-01.js' ] 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('data',function (name) { console.log('请输入用户名:'+name); }) //输出: hello,world 请输入用户名: zhang 请输入用户名:zhang
例子二:
输入任意两个数,自动计算其和
let a; let b; process.stdout.write("请输入a的值:"); process.stdin.on('data',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
正常情况下,无异步操作正在等待,node.js以状态码0退出
未捕捉异常......
详情: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('你好','utf8'); 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('a');//每一个填充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('hex'));// console.log(buf3.toString('utf8'));//你好
(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!

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.

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.

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.

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

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 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 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.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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
Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6
Visual web development tools