珠峰笔记-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

你可能感兴趣的:(珠峰笔记-JavaScript module:CommonJS)