node.js札记
node.js回调函数的设计原则:
1:如果函数需要回调函数参数,一定是在参数的最后面
2:错误优先的回调函数
手工实现node.js的require:
1 function $require(id) { 2 //缓存机制 3 $require.cache = $require.cache || {}; 4 if ($require.cache[id]) { 5 return $require.cache[id].exports; 6 } 7 8 const path = require('path'); 9 const filename = path.join(__dirname, id); 10 const dirname = path.dirname(filename); 11 const fs = require('fs'); 12 let code = fs.readFileSync(filename, 'utf8'); 13 14 const module = {exports: {}}; 15 const exports = module.exports; 16 code = ` 17 (function($require,module,exports,__dirname,__filename){ 18 ${code} 19 })($require,module,exports,dirname,filename) 20 `; 21 eval(code); 22 $require.cache[id] = module; 23 return module.exports; 24 } 25 26 const module1 = $require('./module1.js'); 27 module1.say('hello require...'); 28 const module2 = $require('./module1.js'); 29 module2.say('hello require...');