珠峰笔记-JavaScript module:CommonJS

NodeJS 使用 CommanJS 模块系统,简单模拟实现,新建 app.js,内容如下:

const fs = require('fs')

function req(moduleName) {
    const content = fs.readFileSync(moduleName, 'utf-8')
    const fn = new Function('module', content + '\n return module.exports');
    const module = { exports: {} }
    return fn(module)

}
const string = req('./m.js')
console.log(string)

在同目录下新建 m.js, 内容只有一句: module.exports = "hello",运行 app.js, 显示如下:

lee:apptest$ node app.js 
hello
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。