Skip to content

Latest commit

 

History

History

try-require

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

tryRequire

Wrap require in a try/catch block.

Usage

var tryRequire = require( '@stdlib/utils/try-require' );

tryRequire( id )

Wraps require in a try/catch block. If able to resolve a module id, the function returns the value bound to module.exports in the resolved module. Otherwise, the function returns an Error.

var x = require( 'beep' );

if ( x instanceof Error ) {
    console.log( x.message );
}

Examples

var tryRequire = require( '@stdlib/utils/try-require' );

var out;

out = tryRequire( '_abcdefghijklmnopqrstuvwxyz123456789_' );
if ( out instanceof Error ) {
    console.error( out.message );
} else {
    throw new Error( 'expected an error' );
}

out = tryRequire( '@stdlib/utils/try-require' );
if ( out !== tryRequire ) {
    throw new Error( 'expected export' );
}