Node.js
使用 Node.js 處理目錄並運行 Maven 命令
以下是一段使用 Node.js 處理目錄並在每個目錄中運行 Maven 命令的範例代碼:
import { readdir } from 'fs/promises';
import { join } from 'path';
import { exec } from 'child_process';
const TARGET_FOLDER = process.cwd();
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);
console.log(`Processing directory: ${dirPath}`);
console.log(`Running 'mvn clean install -DskipTests' in ${dirPath}`);
exec('mvn clean install -DskipTests', { cwd: dirPath }, (err, stdout, stderr) => {
if (err) {
console.error(`Error executing Maven in ${dirPath}: ${err.message}`);
return;
}
console.log(`Output for ${dirPath}:\n${stdout}`);
if (stderr) {
console.error(`Errors for ${dirPath}:\n${stderr}`);
} else {
console.log(`Successfully processed ${dirPath}`);
}
});
}
}
} catch (err) {
console.error(`Error reading directory: ${err.message}`);
}
};
processDirectories();
代碼說明
這段代碼的主要功能是遍歷當前工作目錄中的所有子目錄,並在每個子目錄中運行 Maven 命令 mvn clean install -DskipTests。以下是代碼的詳細說明:
- 設置目標文件夾:
const TARGET_FOLDER = process.cwd();設置目標文件夾為當前工作目錄。 - 讀取目錄內容: 使用
readdir函數讀取目標文件夾中的所有文件和子目錄。 - 遍歷文件和子目錄: 使用
for...of迴圈遍歷所有文件和子目錄。 - 檢查是否為目錄: 使用
file.isDirectory()檢查當前項目是否為目錄。 - 運行 Maven 命令: 使用
exec函數在每個目錄中運行 Maven 命令mvn clean install -DskipTests,並處理命令的輸出和錯誤。
這段代碼可以幫助開發者自動化處理多個目錄中的 Maven 構建過程,提高開發效率。
更新 mkdocs.yml 文件
以下是一段使用 Node.js 更新 mkdocs.yml 文件的範例代碼:
import fs from 'fs';
import path from 'path';
import yaml from 'js-yaml';
export function updateMkdocsYml(mkdocsYmlPath, missingMdFilesPath) {
const mkdocsYmlContent = fs.readFileSync(mkdocsYmlPath, 'utf8');
console.log(`Read mkdocs.yml from ${mkdocsYmlPath}`);
const mkdocsYml = yaml.load(mkdocsYmlContent);
const missingMdFiles = fs.readFileSync(missingMdFilesPath, 'utf8').split('\n').filter(Boolean);
if (!mkdocsYml.nav) {
mkdocsYml.nav = [];
}
missingMdFiles.forEach(file => {
const relativePath = file.replace(/^docs[\\/]/, '').replace(new RegExp(`\\${path.sep}`, 'g'), '/'); // 移除 'docs/' 或 'docs\' 前綴
const parts = relativePath.split('/'); // 分割路徑
let currentNav = mkdocsYml.nav;
parts.forEach((part, index) => {
if (index === parts.length - 1) {
const fileName = path.basename(part, '.md').replace("'", "");
console.log(`Adding ${fileName}: ${relativePath}`);
currentNav.push(`${fileName}: ${relativePath}`);
} else {
let subNav = currentNav.find(item => typeof item === 'object' && item[part]);
if (!subNav) {
subNav = { [part]: [] };
currentNav.push(subNav);
}
currentNav = subNav[part];
}
});
});
const newMkdocsYmlContent = yaml.dump(mkdocsYml, { lineWidth: -1 });
const cleanedMkdocsYmlContent = newMkdocsYmlContent.replace(/'([^']+)'/g, '$1');
fs.writeFileSync(mkdocsYmlPath, cleanedMkdocsYmlContent, 'utf8');
console.log(`Added ${missingMdFiles.length} missing .md files to mkdocs.yml`);
fs.unlinkSync(missingMdFilesPath);
console.log('Appended new configuration to mkdocs.yml');
}
代碼說明
這段代碼的主要功能是更新 mkdocs.yml 文件,將缺失的 Markdown 文件路徑添加到導航中。以下是代碼的詳細說明:
- 讀取 mkdocs.yml 文件: 使用
fs.readFileSync函數讀取mkdocs.yml文件的內容。 - 解析 mkdocs.yml 文件: 使用
yaml.load函數將文件內容解析為 JavaScript 對象。 - 讀取缺失的 Markdown 文件列表: 使用
fs.readFileSync函數讀取missing_md_files.txt文件的內容,並將其分割為文件路徑數組。 - 更新導航: 遍歷缺失的 Markdown 文件列表,將每個文件路徑添加到
mkdocs.yml的導航中。 - 處理引號: 使用正則表達式移除導航中的多餘引號。
- 寫入更新後的 mkdocs.yml 文件: 使用
fs.writeFileSync函數將更新後的內容寫入mkdocs.yml文件。 - 刪除缺失文件列表: 使用
fs.unlinkSync函數刪除missing_md_files.txt文件。
這段代碼可以幫助開發者自動化更新 mkdocs.yml 文件,確保所有 Markdown 文件都被正確地包含在導航中。
變更分支
以下是一段使用 Node.js 變更 Git 分支的範例代碼:
import { readdir, stat } from 'fs/promises';
import { join } from 'path';
import { exec } from 'child_process';
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();
代碼說明
這段代碼的主要功能是遍歷當前工作目錄中的所有子目錄,並在每個包含 .git 目錄的子目錄中切換到指定的 Git 分支。以下是代碼的詳細說明:
- 設置分支名稱: 使用
process.argv[2]獲取用戶輸入的分支名稱,默認為dev。 - 設置目標文件夾:
const TARGET_FOLDER = process.cwd();設置目標文件夾為當前工作目錄。 - 讀取目錄內容: 使用
readdir函數讀取目標文件夾中的所有文件和子目錄。 - 遍歷文件和子目錄: 使用
for...of迴圈遍歷所有文件和子目錄。 - 檢查是否包含 .git 目錄: 使用
stat函數檢查子目錄中是否包含.git目錄。 - 切換分支: 使用
exec函數在每個包含.git目錄的子目錄中運行git checkout命令切換分支,並處理命令的輸出和錯誤。
這段代碼可以幫助開發者自動化切換多個目錄中的 Git 分支,提高開發效率。