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!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


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

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

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
