nodekit-io / nodekit-darwin

{NK} NodeKit is the universal, open-source, embedded engine that provides a full ES5 / Node.js instance inside desktop and mobile applications for macOS, iOS, Android, and Windows. [Swift 2.3 Darwin]
http://nodekit.io
Apache License 2.0
22 stars 4 forks source link

Allow require of directory to find directory/index.js #5

Closed patgoley closed 7 years ago

patgoley commented 7 years ago

Standard node require behavior will look for somePath and also somePath/index.js, so NodeKit should probably do the same.

I'm thinking the js implementation of require should be updated to the following:

BootstrapModule.prototype.require = function(id)
{
    if (id == 'native_module') {
        return BootstrapModule;
    }

    if (id[0] == ".")
    {
        id = _absolutePath(this.__dirname + '/', id);
    }

    var cached;

    var isPossibleDirectoryRequire = id.indexOf('index.js') == -1;
    var directoryIndexId = id + '/index.js';

    if (isPossibleDirectoryRequire) {

        cached = BootstrapModule.getCached(directoryIndexId);

        if (cached) {
            return cached.exports
        }
    }

    var cached = BootstrapModule.getCached(id);
    if (cached) {
        return cached.exports;
    }

    process.moduleLoadList.push('BootstrapModule ' + id);

    var bootstrapModule = new BootstrapModule(id);

    bootstrapModule.cache();

    bootstrapModule.load();

    if (Object.keys(bootstrapModule.exports).length == 0 && isPossibleDirectoryRequire {

        return BootstrapModule.require(directoryIndexId)
    }

    return bootstrapModule.exports;
};