| 40 | } |
| 41 | |
| 42 | export function resolveModule(workspaceRoot: string, moduleName: string): Thenable<any> { |
| 43 | interface Message { |
| 44 | command: string; |
| 45 | success?: boolean; |
| 46 | args?: any; |
| 47 | result?: any |
| 48 | } |
| 49 | let nodePathKey: string = 'NODE_PATH'; |
| 50 | return new Promise<any>((resolve, reject) => { |
| 51 | let nodePath: string[] = []; |
| 52 | if (workspaceRoot) { |
| 53 | nodePath.push(path.join(workspaceRoot, 'node_modules')); |
| 54 | } |
| 55 | exec('npm config get prefix', (error: Error, stdout: string, _stderr: string) => { |
| 56 | if (!error) { |
| 57 | let globalPath = stdout.replace(/[\s\r\n]+$/, ''); |
| 58 | if (globalPath.length > 0) { |
| 59 | if (isWindows()) { |
| 60 | nodePath.push(path.join(globalPath, 'node_modules')); |
| 61 | } else { |
| 62 | nodePath.push(path.join(globalPath, 'lib', 'node_modules')); |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | let separator = isWindows() ? ';' : ':'; |
| 67 | let env = process.env; |
| 68 | let newEnv = Object.create(null); |
| 69 | Object.keys(env).forEach(key => newEnv[key] = env[key]); |
| 70 | if (newEnv[nodePathKey]) { |
| 71 | newEnv[nodePathKey] = nodePath.join(separator) + separator + newEnv[nodePathKey]; |
| 72 | } else { |
| 73 | newEnv[nodePathKey] = nodePath.join(separator); |
| 74 | } |
| 75 | try { |
| 76 | let cp: ChildProcess = fork(path.join(__dirname, 'resolve.js'), [], <any>{ env: newEnv, execArgv: [] }); |
| 77 | cp.on('message', (message: Message) => { |
| 78 | if (message.command === 'resolve') { |
| 79 | let toRequire: string = moduleName; |
| 80 | if (message.success) { |
| 81 | toRequire = message.result; |
| 82 | } |
| 83 | cp.send({ command: 'exit' }); |
| 84 | try { |
| 85 | resolve(require(toRequire)); |
| 86 | } catch (error) { |
| 87 | reject(error); |
| 88 | } |
| 89 | } |
| 90 | }); |
| 91 | let message: Message = { |
| 92 | command: 'resolve', |
| 93 | args: moduleName |
| 94 | }; |
| 95 | cp.send(message); |
| 96 | } catch (error) { |
| 97 | reject(error); |
| 98 | } |
| 99 | }); |