export function resolve()

in server/src/node/files.ts [41:118]


export function resolve(moduleName: string, nodePath: string | undefined, cwd: string | undefined, tracer: (message: string, verbose?: string) => void): Promise<string> {
	interface Message {
		c: string;
		s?: boolean;
		a?: any;
		r?: any;
	}

	const nodePathKey: string = 'NODE_PATH';

	const app: string = [
		'var p = process;',
		'p.on(\'message\',function(m){',
		'if(m.c===\'e\'){',
		'p.exit(0);',
		'}',
		'else if(m.c===\'rs\'){',
		'try{',
		'var r=require.resolve(m.a);',
		'p.send({c:\'r\',s:true,r:r});',
		'}',
		'catch(err){',
		'p.send({c:\'r\',s:false});',
		'}',
		'}',
		'});'
	].join('');

	return new Promise<any>((resolve, reject) => {
		let env = process.env;
		let newEnv = Object.create(null);
		Object.keys(env).forEach(key => newEnv[key] = env[key]);

		if (nodePath && fs.existsSync(nodePath) /* see issue 545 */) {
			if (newEnv[nodePathKey]) {
				newEnv[nodePathKey] = nodePath + path.delimiter + newEnv[nodePathKey];
			} else {
				newEnv[nodePathKey] = nodePath;
			}
			if (tracer) {
				tracer(`NODE_PATH value is: ${newEnv[nodePathKey]}`);
			}
		}
		newEnv['ELECTRON_RUN_AS_NODE'] = '1';
		try {
			let cp: ChildProcess = fork('', [], <any>{
				cwd: cwd,
				env: newEnv,
				execArgv: ['-e', app]
			});
			if (cp.pid === void 0) {
				reject(new Error(`Starting process to resolve node module  ${moduleName} failed`));
				return;
			}
			cp.on('error', (error: any) => {
				reject(error);
			});
			cp.on('message', (message: Message) => {
				if (message.c === 'r') {
					cp.send({ c: 'e' });
					if (message.s) {
						resolve(message.r);
					} else {
						reject(new Error(`Failed to resolve module: ${moduleName}`));
					}
				}
			});
			let message: Message = {
				c: 'rs',
				a: moduleName
			};
			cp.send(message);
		} catch (error) {
			reject(error);
		}
	});

}