nodejs-dependencies-install.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. #!/usr/bin/env node
  2. /**
  3. * Node.js 依赖安装和同步脚本
  4. * 功能:检查、安装 package.json 中的依赖,然后同步所有已安装的包到 dependencies.txt
  5. */
  6. const fs = require('fs');
  7. const path = require('path');
  8. const { execSync } = require('child_process');
  9. // 获取脚本所在目录和项目根目录
  10. const scriptDir = __dirname;
  11. const projectRoot = path.dirname(scriptDir);
  12. const packageJsonPath = path.join(projectRoot, 'package.json');
  13. const dependenciesFile = path.join(scriptDir, 'dependencies.txt');
  14. const nodeModulesPath = path.join(projectRoot, 'node_modules');
  15. // 颜色输出函数
  16. const colors = {
  17. reset: '\x1b[0m',
  18. red: '\x1b[31m',
  19. green: '\x1b[32m',
  20. yellow: '\x1b[33m',
  21. cyan: '\x1b[36m',
  22. white: '\x1b[37m'
  23. };
  24. function log(message, color = 'reset') {
  25. console.log(`${colors[color]}${message}${colors.reset}`);
  26. }
  27. // 检查 package.json 是否存在
  28. if (!fs.existsSync(packageJsonPath)) {
  29. log('[X] package.json not found', 'red');
  30. process.exit(1);
  31. }
  32. // 读取 package.json
  33. const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
  34. const allDependencies = {};
  35. // 收集所有依赖
  36. if (packageJson.dependencies) {
  37. Object.keys(packageJson.dependencies).forEach(depName => {
  38. allDependencies[depName] = {
  39. version: packageJson.dependencies[depName],
  40. type: 'dependency'
  41. };
  42. });
  43. }
  44. if (packageJson.devDependencies) {
  45. Object.keys(packageJson.devDependencies).forEach(depName => {
  46. allDependencies[depName] = {
  47. version: packageJson.devDependencies[depName],
  48. type: 'devDependency'
  49. };
  50. });
  51. }
  52. // 检查缺失的依赖
  53. const missingDependencies = [];
  54. let installedCount = 0;
  55. let missingCount = 0;
  56. const depNames = Object.keys(allDependencies).sort();
  57. for (const depName of depNames) {
  58. const packagePath = path.join(nodeModulesPath, depName);
  59. const packageJsonPath = path.join(packagePath, 'package.json');
  60. if (fs.existsSync(packageJsonPath)) {
  61. installedCount++;
  62. } else {
  63. missingDependencies.push(depName);
  64. missingCount++;
  65. }
  66. }
  67. // 如果有缺失的依赖,显示必要信息并安装
  68. if (missingCount > 0) {
  69. log(`[X] Missing ${missingCount} package(s) out of ${Object.keys(allDependencies).length}`, 'red');
  70. log('Missing dependencies:', 'yellow');
  71. missingDependencies.forEach(missing => {
  72. log(` - ${missing}`, 'red');
  73. });
  74. log('\nInstalling missing dependencies...', 'yellow');
  75. try {
  76. // 切换到项目根目录
  77. process.chdir(projectRoot);
  78. // 执行 npm install,隐藏输出
  79. execSync('npm install', {
  80. stdio: 'ignore',
  81. cwd: projectRoot
  82. });
  83. log('[OK] All dependencies installed successfully', 'green');
  84. } catch (error) {
  85. log('[X] Dependency installation failed', 'red');
  86. process.exit(1);
  87. }
  88. } else {
  89. log(`[OK] All dependencies are installed (${Object.keys(allDependencies).length} packages)`, 'green');
  90. }
  91. // 同步所有已安装的依赖到 dependencies.txt
  92. log('\nSyncing all installed dependencies to configs/dependencies.txt...', 'cyan');
  93. const syncResult = [];
  94. if (fs.existsSync(nodeModulesPath)) {
  95. // 遍历 node_modules 目录,查找所有 package.json 文件
  96. function findPackageJsonFiles(dir) {
  97. const files = [];
  98. try {
  99. const entries = fs.readdirSync(dir, { withFileTypes: true });
  100. for (const entry of entries) {
  101. const fullPath = path.join(dir, entry.name);
  102. if (entry.isDirectory()) {
  103. // 跳过 .bin 目录和其他特殊目录
  104. if (entry.name.startsWith('.') || entry.name === 'node_modules') {
  105. continue;
  106. }
  107. // 递归查找
  108. files.push(...findPackageJsonFiles(fullPath));
  109. } else if (entry.name === 'package.json') {
  110. files.push(fullPath);
  111. }
  112. }
  113. } catch (error) {
  114. // 忽略权限错误等
  115. }
  116. return files;
  117. }
  118. const packageJsonFiles = findPackageJsonFiles(nodeModulesPath);
  119. for (const file of packageJsonFiles) {
  120. try {
  121. const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
  122. if (pkg.name && pkg.version) {
  123. syncResult.push(`${pkg.name}==${pkg.version}`);
  124. }
  125. } catch (error) {
  126. // 忽略解析错误
  127. }
  128. }
  129. // 如果遍历结果为空,使用 npm list 作为后备方案
  130. if (syncResult.length === 0) {
  131. try {
  132. const npmListOutput = execSync('npm list --depth=0 --json', {
  133. encoding: 'utf-8',
  134. cwd: projectRoot,
  135. stdio: ['ignore', 'pipe', 'ignore']
  136. });
  137. const npmList = JSON.parse(npmListOutput);
  138. if (npmList.dependencies) {
  139. Object.keys(npmList.dependencies).forEach(depName => {
  140. const dep = npmList.dependencies[depName];
  141. if (dep && dep.version) {
  142. syncResult.push(`${depName}==${dep.version}`);
  143. }
  144. });
  145. }
  146. } catch (error) {
  147. // 忽略错误
  148. }
  149. }
  150. } else {
  151. // 如果 node_modules 不存在,使用 npm list
  152. try {
  153. const npmListOutput = execSync('npm list --depth=0 --json', {
  154. encoding: 'utf-8',
  155. cwd: projectRoot,
  156. stdio: ['ignore', 'pipe', 'ignore']
  157. });
  158. const npmList = JSON.parse(npmListOutput);
  159. if (npmList.dependencies) {
  160. Object.keys(npmList.dependencies).forEach(depName => {
  161. const dep = npmList.dependencies[depName];
  162. if (dep && dep.version) {
  163. syncResult.push(`${depName}==${dep.version}`);
  164. }
  165. });
  166. }
  167. } catch (error) {
  168. // 忽略错误
  169. }
  170. }
  171. // 去重并排序
  172. const uniqueResult = [...new Set(syncResult)].sort();
  173. // 写入文件(UTF-8 编码)
  174. fs.writeFileSync(dependenciesFile, uniqueResult.join('\n') + '\n', 'utf-8');
  175. log(`[OK] Dependencies synced to ${dependenciesFile} (${uniqueResult.length} packages)`, 'green');
  176. process.exit(0);