diff --git a/src/utils.test.ts b/src/utils.test.ts new file mode 100644 index 00000000..0f621c81 --- /dev/null +++ b/src/utils.test.ts @@ -0,0 +1,47 @@ +/** + * Copyright (c) 2018, Microsoft Corporation (MIT License). + */ + +import * as assert from 'assert'; +import * as path from 'path'; +import { loadNativeModule } from './utils'; + +const nativeName = process.platform === 'win32' ? 'conpty' : 'pty'; + +describe('utils', () => { + describe('loadNativeModule', () => { + afterEach(() => { + delete process.env.NODE_PTY_PREBUILT_PATH; + }); + + it('should load from NODE_PTY_PREBUILT_PATH when set to a valid path', () => { + const validPath = path.resolve(__dirname, '..', 'build', 'Release'); + process.env.NODE_PTY_PREBUILT_PATH = validPath; + const result = loadNativeModule(nativeName); + assert.strictEqual(result.dir, validPath); + assert.ok(result.module); + }); + + it('should fall through to default paths when NODE_PTY_PREBUILT_PATH is invalid', () => { + process.env.NODE_PTY_PREBUILT_PATH = '/nonexistent/path'; + const result = loadNativeModule(nativeName); + assert.ok(result.dir !== '/nonexistent/path'); + assert.ok(result.module); + }); + + it('should load normally when NODE_PTY_PREBUILT_PATH is not set', () => { + delete process.env.NODE_PTY_PREBUILT_PATH; + const result = loadNativeModule(nativeName); + assert.ok(result.dir); + assert.ok(result.module); + }); + + it('should include NODE_PTY_PREBUILT_PATH in error message when all paths fail', () => { + process.env.NODE_PTY_PREBUILT_PATH = '/nonexistent/path'; + assert.throws( + () => loadNativeModule('does-not-exist'), + (err: Error) => err.message.includes('/nonexistent/path') + ); + }); + }); +}); diff --git a/src/utils.ts b/src/utils.ts index 1d2d7c93..38683233 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -10,6 +10,16 @@ export function assign(target: any, ...sources: any[]): any { export function loadNativeModule(name: string): {dir: string, module: any} { + // Allow overriding the prebuilt path via environment variable + const envPath = process.env.NODE_PTY_PREBUILT_PATH; + if (envPath) { + try { + return { dir: envPath, module: require(`${envPath}/${name}.node`) }; + } catch (e) { + // Fall through to default paths + } + } + // Check build, debug, and then prebuilds. const dirs = ['build/Release', 'build/Debug', `prebuilds/${process.platform}-${process.arch}`]; // Check relative to the parent dir for unbundled and then the current dir for bundled @@ -25,5 +35,5 @@ export function loadNativeModule(name: string): {dir: string, module: any} { } } } - throw new Error(`Failed to load native module: ${name}.node, checked: ${dirs.join(', ')}: ${lastError}`); + throw new Error(`Failed to load native module: ${name}.node, checked: ${envPath ? envPath + ', ' : ''}${dirs.join(', ')}: ${lastError}`); }