打包指令
要使 ch 指令接收參數,你可以在 ch.js 中使用 process.argv 來獲取命令行參數。這樣,你可以在運行 ch 指令時傳遞參數,並在腳本中使用這些參數。
以下是具體步驟:
1. 確保 ch.js 文件可以接收參數
修改你的 ch.js 文件,使其可以接收參數:
#!/usr/bin/env node
import { readdir, stat } from 'fs/promises';
import { join } from 'path';
import { exec } from 'child_process';
// 获取用户输入的分支名称,默认为 'dev'
const branchName = process.argv[2] || 'dev';
const TARGET_FOLDER = process.cwd();
const switchToBranch = async (dirPath, branch) => {
return new Promise((resolve, reject) => {
exec(`git checkout ${branch}`, { cwd: dirPath }, (err, stdout, stderr) => {
if (err) {
reject(`Error switching to ${branch} branch in ${dirPath}: ${err.message}`);
return;
}
resolve(`Switched to ${branch} branch in ${dirPath}`);
});
});
};
const processDirectories = async () => {
try {
const files = await readdir(TARGET_FOLDER, { withFileTypes: true });
for (const file of files) {
if (file.isDirectory()) {
const dirPath = join(TARGET_FOLDER, file.name);
const gitPath = join(dirPath, '.git');
try {
const gitStat = await stat(gitPath);
if (gitStat.isDirectory()) {
const result = await switchToBranch(dirPath, branchName);
console.log(result);
}
} catch (err) {
// .git directory does not exist, skip
}
}
}
} catch (err) {
console.error(`Error reading directory: ${err.message}`);
}
};
processDirectories();
2. 在 package.json 中配置 bin 字段
確保你的 package.json 中有 bin 字段來配置可執行文件:
{
"name": "your-package-name",
"version": "1.0.0",
"description": "",
"main": "ch.js",
"bin": {
"ch": "./ch.js"
},
"scripts": {
"run-scripts": "ch && echo 'ch.js executed' && node another.js"
},
"author": "",
"license": "ISC"
}
3. 全局安裝你的 npm 包
在你的項目目錄中運行以下命令來全局安裝你的 npm 包:
npm install -g .
4. 使用 ch 指令並傳遞參數
現在,你可以在命令行中使用 ch 指令並傳遞參數。例如:
ch feature-branch
在這個命令中,feature-branch 會作為參數傳遞給 ch.js,你可以在 ch.js 中通過 process.argv[2] 獲取這個參數。
hashbang
#!/usr/bin/env node 是一行 shebang(也稱為 hashbang),它告訴操作系統使用哪個解釋器來運行這個腳本。在這種情況下,它指定使用 Node.js 來運行這個腳本。
作用
-
指定解釋器:這行 shebang 告訴操作系統,當這個腳本被執行時,應該使用
node命令來解釋和運行這個腳本。/usr/bin/env是一個通用的方法來查找node可執行文件的位置,這樣可以確保腳本在不同的系統環境中都能正常運行。 -
使腳本可執行:當你在命令行中直接運行這個腳本時,例如
./ch.js,操作系統會讀取這行 shebang 並使用指定的解釋器來運行腳本。
示例
假設你的 ch.js 文件如下:
#!/usr/bin/env node
console.log('Hello, world!');
使用方法
-
添加執行權限:確保腳本文件具有可執行權限。你可以使用以下命令來添加執行權限:
chmod +x ch.js -
直接運行腳本:現在你可以在命令行中直接運行這個腳本:
./ch.js
這樣,操作系統會使用 Node.js 來解釋和運行 ch.js 文件中的代碼,並輸出 Hello, world!。
總結
#!/usr/bin/env node 行的主要作用是指定使用 Node.js 來運行這個腳本,並使腳本可以在命令行中直接執行。這樣可以確保你的腳本在不同的系統環境中都能正常運行。