process
process 对象提供有关当前 Node.js 进程的信息并对其进行控制。类似于浏览器环境下的window对象。
对于开发人员常用的有:
- 命令行参数获取:
process.argv
属性可以获取在启动 Node.js 进程时传入的命令行参数。这对于根据不同的参数执行不同的逻辑非常有用。 - 环境变量访问:
process.env
对象包含了当前进程的环境变量。你可以使用它来访问和设置环境变量,例如获取数据库的连接字符串等。 - 进程退出控制:
process.exit()
方法可以用于退出当前 Node.js 进程。你可以在必要时使用它来终止程序的执行。 - 事件循环控制:
process.nextTick()
方法可以将回调函数放在事件循环的下一个周期执行。这对于执行延迟或优先级较高的任务非常有用。 - 信号处理:
process.on()
方法可以用于处理不同类型的信号,如捕获键盘中断(SIGINT)信号以执行清理操作等。 - 标准输入/输出流:
process.stdin
和process.stdout
对象用于读取标准输入和向标准输出写入数据。 - 进程信息获取:
process.pid
属性可以获取当前进程的 PID(进程ID),process.cwd()
方法可以获取当前进程的工作目录等。 - 内存使用情况:
process.memoryUsage()
方法用于获取当前进程的内存使用情况,包括堆、堆外内存的使用情况等。
打印process对象
写一个node脚本tmp.js
const fs = require("fs");
const util = require("util");
const formattedProcess = util.inspect(process);
fs.writeFileSync("./txt.js", formattedProcess);
通过 util.inspect()
方法将 process
对象转换为格式化后的字符串,然后将该字符串写入到 txt.js
文件中。这样可以确保将 process
对象的详细信息保存到文件中。
结果如下:
process {
version: 'v18.2.0',
versions: {
node: '18.2.0',
v8: '10.1.124.8-node.13',
uv: '1.43.0',
zlib: '1.2.11',
brotli: '1.0.9',
ares: '1.18.1',
modules: '108',
nghttp2: '1.47.0',
napi: '8',
llhttp: '6.0.6',
openssl: '3.0.3+quic',
cldr: '41.0',
icu: '71.1',
tz: '2022a',
unicode: '14.0',
ngtcp2: '0.1.0-DEV',
nghttp3: '0.1.0-DEV'
},
arch: 'x64',
platform: 'win32',
release: {
name: 'node',
sourceUrl: 'https://nodejs.org/download/release/v18.2.0/node-v18.2.0.tar.gz',
headersUrl: 'https://nodejs.org/download/release/v18.2.0/node-v18.2.0-headers.tar.gz',
libUrl: 'https://nodejs.org/download/release/v18.2.0/win-x64/node.lib'
},
_rawDebug: [Function: _rawDebug],
moduleLoadList: [
'Internal Binding native_module',
],
binding: [Function: binding],
_linkedBinding: [Function: _linkedBinding],
_events: [Object: null prototype] {
newListener: [Function: startListeningIfSignal],
removeListener: [Function: stopListeningIfSignal],
warning: [Function: onWarning]
},
_eventsCount: 3,
_maxListeners: undefined,
domain: null,
_exiting: false,
config: [Getter/Setter],
dlopen: [Function: dlopen],
uptime: [Function: uptime],
_getActiveRequests: [Function: _getActiveRequests],
_getActiveHandles: [Function: _getActiveHandles],
getActiveResourcesInfo: [Function (anonymous)],
reallyExit: [Function: reallyExit],
_kill: [Function: _kill],
cpuUsage: [Function: cpuUsage],
resourceUsage: [Function: resourceUsage],
memoryUsage: [Function: memoryUsage] { rss: [Function: rss] },
kill: [Function: kill],
exit: [Function: exit],
hrtime: [Function: hrtime] { bigint: [Function: hrtimeBigInt] },
openStdin: [Function (anonymous)],
allowedNodeEnvironmentFlags: [Getter/Setter],
assert: [Function: deprecated],
features: {
inspector: true,
debug: false,
uv: true,
ipv6: true,
tls_alpn: true,
tls_sni: true,
tls_ocsp: true,
tls: true,
cached_builtins: [Getter]
},
_fatalException: [Function (anonymous)],
setUncaughtExceptionCaptureCallback: [Function: setUncaughtExceptionCaptureCallback],
hasUncaughtExceptionCaptureCallback: [Function: hasUncaughtExceptionCaptureCallback],
emitWarning: [Function: emitWarning],
nextTick: [Function: nextTick],
_tickCallback: [Function: runNextTicks],
_debugProcess: [Function: _debugProcess],
_debugEnd: [Function: _debugEnd],
_startProfilerIdleNotifier: [Function (anonymous)],
_stopProfilerIdleNotifier: [Function (anonymous)],
stdout: [Getter],
stdin: [Getter],
stderr: [Getter],
abort: [Function: abort],
umask: [Function: wrappedUmask],
chdir: [Function (anonymous)],
cwd: [Function: wrappedCwd],
env: {
ALLUSERSPROFILE: 'C:\\ProgramData',
APPDATA: 'C:\\Users\\admin\\AppData\\Roaming',
ChocolateyInstall: 'C:\\ProgramData\\chocolatey',
NVM_HOME: 'C:\\Program Files\\nvm',
NVM_SYMLINK: 'C:\\Program Files\\nodejs',
OneDrive: 'C:\\Users\\admin\\OneDrive',
ORIGINAL_XDG_CURRENT_DESKTOP: 'undefined',
OS: 'Windows_NT',
Path: 'C:\\Users\\admin\\AppData\\Local\\oh-my-posh;C:\\Program Files\\PowerShell\\7;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Windows\\System32\\OpenSSH\\;C:\\Program Files\\NVIDIA Corporation\\NVIDIA NvDLISR;C:\\ProgramData\\chocolatey\\bin;C:\\Program Files\\PuTTY\\;C:\\Program Files (x86)\\NVIDIA Corporation\\PhysX\\Common;C:\\Program Files\\dotnet\\;C:\\Program Files\\nvm;C:\\Program Files\\nodejs;C:\\Program Files (x86)\\nodejs\\;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Program Files (x86)\\Tencent\\微信web开发者工具\\dll;C:\\Pro;C:\\neovim\\bin;C:\\Program Files\\Git\\cmd;C:\\Program Files\\Docker\\Docker\\resources\\bin;C:\\Program Files\\PowerShell\\7\\;C:\\Users\\admin\\AppData\\Local\\pnpm;C:\\Users\\admin\\scoop\\apps\\mingw\\current\\bin;C:\\Users\\admin\\scoop\\apps\\llvm\\current\\bin;C:\\Users\\admin\\scoop\\apps\\gcc\\current\\bin;C:\\Users\\admin\\scoop\\shims;C:\\Users\\admin\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\admin\\AppData\\Roaming\\npm;C:\\Users\\admin\\AppData\\Local\\Programs\\Fiddler;C:\\Users\\admin\\AppData\\Local\\Programs\\Microsoft VS Code\\bin;C:\\Users\\admin\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\admin\\AppData\\Local\\Programs\\oh-my-posh\\bin;C:\\Program Files\\JetBrains\\WebStorm 2023.1.2\\bin;C:\\Users\\admin\\AppData\\Local\\Programs\\Microsoft VS Code Insiders\\bin',
PATHEXT: '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL',
POWERLINE_COMMAND: 'oh-my-posh',
POWERSHELL_DISTRIBUTION_CHANNEL: 'MSI:Windows 10 Home China',
PROCESSOR_ARCHITECTURE: 'AMD64',
PROCESSOR_IDENTIFIER: 'Intel64 Family 6 Model 140 Stepping 2, GenuineIntel',
PROCESSOR_LEVEL: '6',
PROCESSOR_REVISION: '8c02',
ProgramData: 'C:\\ProgramData',
ProgramFiles: 'C:\\Program Files',
'ProgramFiles(x86)': 'C:\\Program Files (x86)',
ProgramW6432: 'C:\\Program Files',
PSModulePath: 'C:\\Users\\admin\\Documents\\PowerShell\\Modules;C:\\Program Files\\PowerShell\\Modules;c:\\program files\\powershell\\7\\Modules;C:\\Program Files\\WindowsPowerShell\\Modules;C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\Modules',
PUBLIC: 'C:\\Users\\Public',
USERNAME: 'admin',
USERPROFILE: 'C:\\Users\\admin',
},
title: 'pwsh in temp',
argv: [
'C:\\Program Files\\nodejs\\node.exe',
'C:\\Users\\admin\\Desktop\\ruochuan\\dotenv\\temp\\tmp.js'
],
execArgv: [],
pid: 2020,
ppid: 16652,
execPath: 'C:\\Program Files\\nodejs\\node.exe',
debugPort: 59955,
argv0: 'C:\\Program Files\\nodejs\\node.exe',
exitCode: undefined,
_preload_modules: [
'c:/Users/admin/AppData/Roaming/Code/User/workspaceStorage/0c18065fa56b4a2f88d42a9136f5383c/ms-vscode.js-debug/bootloader.js'
],
report: [Getter],
setSourceMapsEnabled: [Function: setSourceMapsEnabled],
mainModule: Module {
id: '.',
path: 'C:\\Users\\admin\\Desktop\\ruochuan\\dotenv\\temp',
exports: {},
filename: 'C:\\Users\\admin\\Desktop\\ruochuan\\dotenv\\temp\\tmp.js',
loaded: false,
children: [],
paths: [
'C:\\Users\\admin\\Desktop\\ruochuan\\dotenv\\temp\\node_modules',
'C:\\Users\\admin\\Desktop\\ruochuan\\dotenv\\node_modules',
'C:\\Users\\admin\\Desktop\\ruochuan\\node_modules',
'C:\\Users\\admin\\Desktop\\node_modules',
'C:\\Users\\admin\\node_modules',
'C:\\Users\\node_modules',
'C:\\node_modules'
]
},
[Symbol(kCapture)]: false
}
以下是对process
对象的部分属性的注释:
-
version
: Node.js的版本号 -
cwd
: 返回当前工作目录的函数 -
env
: 包含有关进程环境变量的对象 -
platform
: Node.js运行的操作系统平台 -
arch
: Node.js运行的体系结构 -
release
: 包含与Node.js发行版相关的信息的对象,例如源代码和库的下载 -
cpuUsage
: 返回有关CPU使用情况的对象 -
resourceUsage
: 返回有关进程资源使用情况的对象 -
memoryUsage
: 返回有关内存使用情况的对象 -
kill
: 用于终止指定进程的函数 -
exit
: 用于终止当前进程的函数 -
allowedNodeEnvironmentFlags
: Node.js环境变量的白名单对象 -
nextTick
: 在事件循环的下一个迭代中执行回调函数的函数 -
stdout
: 标准输出流(Writable
对象)的访问器 -
stdin
: 标准输入流(Readable
对象)的访问器 -
stderr
: 标准错误流(Writable
对象)的访问器 -
abort
: 中止进程的函数 -
umask
: 获取或设置进程的umask值的函数 -
chdir
: 改变当前工作目录的函数 -
title
: 用于设置或获取进程的标题的字符串 -
argv
: 包含命令行参数的数组 -
pid
: 当前进程的ID -
ppid
: 父进程的ID -
execPath
: Node.js可执行文件的绝对路径 -
debugPort
: 调试器监听的端口号 -
argv0
: Node.js可执行文件的名称 -
exitCode
: 进程的退出代码
一些属性具体含义
- os.homedir()
-
process.version 版本
-
process.platform 获取运行系统
值 | 系统 |
---|---|
win32 | Windows |
darwin | macOS |
linux | linux |
- process.argv 命令行参数获取
可以获取在启动 Node.js 进程时传入的命令行参数。这对于根据不同的参数执行不同的逻辑非常有用。
例如:上述tmp.js文件,运行node tmp.js 1 2
,process.argv可以获取运行参数
- process.env 环境变量访问
const fs = require("fs");
const util = require("util");
// 添加环境变量
process.env.AAA = 'hahaha'
const formattedProcess = util.inspect(process);
fs.writeFileSync("./txt.js", formattedProcess);
包含了当前进程的环境变量。你可以使用它来访问和设置环境变量,例如获取数据库的连接字符串等。
- process.exit 进程退出控制 可以用于退出当前 Node.js 进程。你可以在必要时使用它来终止程序的执行。
path模块
path路径相关操作。
- path.resolve
将路径或路径片段的序列解析为绝对路径
- path.join
使用特定于平台的分隔符作为定界符将所有给定的 path
片段连接在一起,然后规范化生成的路径。
- path.relative(from, to)
根据当前工作目录返回从 from
到 to
的相对路径。 如果 from
和 to
都解析为相同的路径(在分别调用 path.resolve()
之后),则返回零长度字符串。
- path.sed
提供特定于平台的路径片段分隔符:
- Windows 上是
\
- POSIX 上是
/
- path.normalize(path)
当找到多个连续的路径片段分隔符(例如 POSIX 上的 /
和 Windows 上的 或 `/`)时,则它们将被平台特定路径片段分隔符(POSIX 上的 `/` 和 Windows 上的
)的单个实例替换。 保留尾随的分隔符。
当路径中出现多余的分隔符,或者尾部需要返回上一层,会返回上一层路径
crypto模块
加密写个案例
const crypto = require("crypto");
function encrypt(plaintext, keyStr) {
// 将密钥字符串转换为Buffer,并截取后64个字符作为密钥
const key = Buffer.from(keyStr.slice(-64), "hex");
// 生成随机的12字节nonce
const nonce = crypto.randomBytes(12);
try {
// 创建AES-GCM加密器,使用密钥和nonce进行初始化
const aesgcm = crypto.createCipheriv("aes-256-gcm", key, nonce);
// 执行加密操作,并获取加密后的密文和认证标签
let encrypted = aesgcm.update(plaintext);
encrypted = Buffer.concat([encrypted, aesgcm.final()]);
const authTag = aesgcm.getAuthTag();
// 拼接nonce和认证标签到密文中
const ciphertext = Buffer.concat([nonce, encrypted, authTag]);
// 返回Base64编码后的密文
return ciphertext.toString("base64");
} catch (error) {
console.error("加密失败:", error.message);
throw error;
}
}
function decrypt(encrypted, keyStr) {
// 将密钥字符串转换为Buffer,并截取后64个字符作为密钥
const key = Buffer.from(keyStr.slice(-64), "hex");
// 将密文转换为Buffer
let ciphertext = Buffer.from(encrypted, "base64");
// 从密文中提取nonce(前12个字节)和认证标签(最后16个字节)
const nonce = ciphertext.slice(0, 12);
const authTag = ciphertext.slice(-16);
// 截取除去nonce和认证标签之外的部分作为待解密的密文
ciphertext = ciphertext.slice(12, -16);
try {
// 创建AES-GCM解密器,使用密钥和nonce进行初始化
const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
// 设置解密器的认证标签
aesgcm.setAuthTag(authTag);
// 执行解密操作,并返回解密后的明文
return Buffer.concat([
aesgcm.update(ciphertext),
aesgcm.final(),
]).toString();
} catch (error) {
console.error("解密失败:", error.message);
throw error;
}
}
// 输入示例
const plaintext = "ALPHA=zeta";
const key = "ddcaa26504cd70a6fef9801901c3981538563a1767c297cb8416e8a38c62fe00";
try {
// 加密明文
const encryptedText = encrypt(plaintext, key);
// 解密密文
const decryptedText = decrypt(encryptedText, key);
// 输出示例
console.log("明文:", plaintext);
console.log("密钥:", key);
console.log("密文:", encryptedText);
console.log("解密后的明文:", decryptedText);
} catch (error) {
console.error("加密解密过程出错:", error.message);
}
fs模块
fs 模块能够以标准 POSIX 函数为模型的方式与文件系统进行交互。
- fs.statSync 每个文件都带有一组详细信息,我们可以使用 Node.js 检查这些详细信息。
- fs.readFileSync
读取文件信息
child_process 子进程
import { spawn } from 'child_process';
import iconv from 'iconv-lite';// 解决乱码问题
const ls = spawn('cmd.exe', ['/c', 'dir']);
// 监听子进程的标准输出
ls.stdout.on('data', (data) => {
const output = iconv.decode(data, 'gbk');
console.log(`stdout: ${output}`);
});
// 监听子进程的标准错误输出
ls.stderr.on('data', (data) => {
const output = iconv.decode(data, 'gbk');
console.error(`stderr: ${output}`);
});
// 监听子进程的关闭事件
ls.on('close', (code) => {
console.log(`子进程退出,退出码 ${code}`);
});
fileURLToPath
用于将文件的URL转换为文件路径
import {fileURLToPath} from 'url';
const fileURL = new URL('file://path/to/file.txt');
const filePath = fileURLToPath(fileURL);
console.log(filePath); // 输出: /path/to/file.txt
format函数
从Node.js的内置模块util
中导入了format
函数。format
函数用于按照指定的格式字符串将参数格式化为字符串。
import {format} from 'util';
const greeting = format('Hello %s!', 'World');
console.log(greeting); // 输出: Hello World!
持续更新中...