nodejs-dependencies-install.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. // 快速获取已安装的包列表(直接从 node_modules 文件夹读取)
  53. function getInstalledPackagesFromFilesystem() {
  54. const installedPackages = new Set();
  55. if (!fs.existsSync(nodeModulesPath)) {
  56. return installedPackages;
  57. }
  58. try {
  59. const entries = fs.readdirSync(nodeModulesPath, { withFileTypes: true });
  60. for (const entry of entries) {
  61. if (entry.isDirectory()) {
  62. const packageName = entry.name;
  63. // 跳过特殊目录
  64. if (packageName.startsWith('.') || packageName === 'node_modules') {
  65. continue;
  66. }
  67. // 检查是否是有效的包(有 package.json)
  68. const packageJsonPath = path.join(nodeModulesPath, packageName, 'package.json');
  69. if (fs.existsSync(packageJsonPath)) {
  70. installedPackages.add(packageName.toLowerCase());
  71. }
  72. // 处理 scoped 包(如 @babel/core)
  73. if (packageName.startsWith('@')) {
  74. try {
  75. const scopedPath = path.join(nodeModulesPath, packageName);
  76. const scopedEntries = fs.readdirSync(scopedPath, { withFileTypes: true });
  77. for (const scopedEntry of scopedEntries) {
  78. if (scopedEntry.isDirectory()) {
  79. const scopedPackageName = `${packageName}/${scopedEntry.name}`;
  80. const scopedPackageJsonPath = path.join(scopedPath, scopedEntry.name, 'package.json');
  81. if (fs.existsSync(scopedPackageJsonPath)) {
  82. installedPackages.add(scopedPackageName.toLowerCase());
  83. }
  84. }
  85. }
  86. } catch (error) {
  87. // 忽略错误
  88. }
  89. }
  90. }
  91. }
  92. } catch (error) {
  93. // 忽略错误
  94. }
  95. return installedPackages;
  96. }
  97. // 快速检查缺失的依赖(使用文件系统)
  98. const missingDependencies = [];
  99. let installedCount = 0;
  100. let missingCount = 0;
  101. // 一次性获取所有已安装的包(只检查一次文件系统)
  102. const installedPackagesSet = getInstalledPackagesFromFilesystem();
  103. const depNames = Object.keys(allDependencies).sort();
  104. for (const depName of depNames) {
  105. const depNameLower = depName.toLowerCase();
  106. // 快速检查(使用已获取的集合)
  107. if (installedPackagesSet.has(depNameLower)) {
  108. installedCount++;
  109. } else {
  110. missingDependencies.push(depName);
  111. missingCount++;
  112. }
  113. }
  114. // 如果有缺失的依赖,显示必要信息并安装
  115. if (missingCount > 0) {
  116. log(`[X] Missing ${missingCount} package(s) out of ${Object.keys(allDependencies).length}`, 'red');
  117. log('Missing dependencies:', 'yellow');
  118. missingDependencies.forEach(missing => {
  119. log(` - ${missing}`, 'red');
  120. });
  121. log('\nInstalling missing dependencies...', 'yellow');
  122. try {
  123. // 切换到项目根目录
  124. process.chdir(projectRoot);
  125. // 执行 npm install,隐藏输出
  126. execSync('npm install', {
  127. stdio: 'ignore',
  128. cwd: projectRoot
  129. });
  130. log('[OK] All dependencies installed successfully', 'green');
  131. } catch (error) {
  132. log('[X] Dependency installation failed', 'red');
  133. process.exit(1);
  134. }
  135. } else {
  136. log(`[OK] All dependencies are installed (${Object.keys(allDependencies).length} packages)`, 'green');
  137. }
  138. // 快速同步所有已安装的依赖到 dependencies.txt(只读取根级包,静默执行)
  139. function syncInstalledPackagesToFile() {
  140. const syncResult = [];
  141. if (!fs.existsSync(nodeModulesPath)) {
  142. return syncResult;
  143. }
  144. try {
  145. const entries = fs.readdirSync(nodeModulesPath, { withFileTypes: true });
  146. for (const entry of entries) {
  147. if (entry.isDirectory()) {
  148. const packageName = entry.name;
  149. // 跳过特殊目录
  150. if (packageName.startsWith('.') || packageName === 'node_modules') {
  151. continue;
  152. }
  153. // 处理普通包
  154. const packageJsonPath = path.join(nodeModulesPath, packageName, 'package.json');
  155. if (fs.existsSync(packageJsonPath)) {
  156. try {
  157. const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
  158. if (pkg.name && pkg.version) {
  159. syncResult.push(`${pkg.name}==${pkg.version}`);
  160. }
  161. } catch (error) {
  162. // 忽略解析错误
  163. }
  164. }
  165. // 处理 scoped 包(如 @babel/core)
  166. if (packageName.startsWith('@')) {
  167. try {
  168. const scopedPath = path.join(nodeModulesPath, packageName);
  169. const scopedEntries = fs.readdirSync(scopedPath, { withFileTypes: true });
  170. for (const scopedEntry of scopedEntries) {
  171. if (scopedEntry.isDirectory()) {
  172. const scopedPackageJsonPath = path.join(scopedPath, scopedEntry.name, 'package.json');
  173. if (fs.existsSync(scopedPackageJsonPath)) {
  174. try {
  175. const pkg = JSON.parse(fs.readFileSync(scopedPackageJsonPath, 'utf-8'));
  176. if (pkg.name && pkg.version) {
  177. syncResult.push(`${pkg.name}==${pkg.version}`);
  178. }
  179. } catch (error) {
  180. // 忽略解析错误
  181. }
  182. }
  183. }
  184. }
  185. } catch (error) {
  186. // 忽略错误
  187. }
  188. }
  189. }
  190. }
  191. } catch (error) {
  192. // 忽略错误
  193. }
  194. return syncResult;
  195. }
  196. // 同步所有已安装的依赖到 dependencies.txt(快速方法,静默执行)
  197. const syncResult = syncInstalledPackagesToFile();
  198. // 去重并排序
  199. const uniqueResult = [...new Set(syncResult)].sort();
  200. // 写入文件(UTF-8 编码)
  201. fs.writeFileSync(dependenciesFile, uniqueResult.join('\n') + '\n', 'utf-8');
  202. process.exit(0);