读取命令行参数
-
安转minimist(轻量级的命令行参数解析引擎)
npm install --save minimist
-
js文件
javascript
const minimist =require("minimist");
const args = minimist(process.argv.slice(2));
console.log(args["id"])
- package.json
javascript
{
"name": "nodejs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "node index.js --id=10",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@types/node": "^18.0.6",
"minimist": "^1.2.8",
"node-fetch": "^3.2.6"
}
}
- 运行结果
读取package.json文件内容
javascript
const fs=require("fs");
const packageJsonData = JSON.parse(fs.readFileSync("package.json", "utf8"));
console.log(packageJsonData);
退出进程
javascript
process.exit();
使用虚拟dom获取元素
javascript
npm install --save jsdom
javascript
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
console.log(dom.window.document.querySelector("p").textContent); // "Hello world"
处理接口跨域
javascript
res.setHeader("Access-Control-Allow-Origin", "*");