简单Node.js超编程

24 阅读1分钟

我用的是微软Visual Studio Code

首先创建文件夹module,用于存放各个用户自定义程序

在./module下,创建源代码文件mdplugin.js

module.exports = function (_a,_b) {

    return Math.pow(_a, _b);

}

源代码结束

在./module下,创建源代码文件mdtest.js

var _moduleplugin = require('./mdplugin');

module.exports = function (_a, _b, _c) {

    if (_moduleplugin(_a, _b) == _c) {

        console.log('Test OK!');

        return 1;

    } else

    {

        console.log('Test Failed');

    }

    return 0;

}

源代码结束

在项目根目录./下,创建可复用源代码文件load_dir.js

var fs = require('fs');

var path = require('path');

var load = function(path, name) {

    if (name) {

        return require(path + name);

    }

    return require(path)

};

module.exports = function (dir) {

    patcher = {}

    fs.readdirSync(__dirname + '/' + dir).forEach(function (filename) {

        if (!/.js$/.test(filename)) {

            return;

        }

        var name = path.basename(filename, '.js');

        var _load = load.bind(null, './' + dir + '/', name);

        patcher.defineGetter (name, _load);

    });

    return patcher;

}

源代码结束

在项目根目录./下,创建源代码文件appentry.js

var loadDir = require('./load_dir');

var Modules = loadDir('module');

var _testres = Modules.mdtest(2,3,8);

if ( _testres == 1 ) {

    console.log('Test Module Output : OK');

} else

{

    console.log('Test Module Output : Failed');

}

var _plugres = Modules.mdplugin(5,4);

console.log('Plugin Module Output : ' + _plugres);

源代码结束

运行appentry.js

输出结果

Test OK!

Test Module Output : OK

Plugin Module Output : 625

IT人朋友们可修改例子里面的几个数字,观察运行结果变化