Skip to content

Instantly share code, notes, and snippets.

@wulucxy
Last active February 9, 2020 02:14
Show Gist options
  • Save wulucxy/ea1297bd0b0f8cffc39829ec8b9ef7fe to your computer and use it in GitHub Desktop.
Save wulucxy/ea1297bd0b0f8cffc39829ec8b9ef7fe to your computer and use it in GitHub Desktop.
#javascript
/**
* Add event listeners on an `EventEmitter` using a map of <event, listener>
* pairs.
*
* @param {EventEmitter} server The event emitter
* @param {Object.<String, Function>} map The listeners to add
* @return {Function} A function that will remove the added listeners when called
* @private
*/
function addListeners(server, map) {
for (const event of Object.keys(map)) server.on(event, map[event]);
return function removeListeners() {
for (const event of Object.keys(map)) {
server.removeListener(event, map[event]);
}
};
}
/**
* Check if it's hidden.
*/
function isHidden (root, path) {
path = path.substr(root.length).split(sep)
for (let i = 0; i < path.length; i++) {
if (path[i][0] === '.') return true
}
return false
}
// 查看请求体是否有内容
var hasBody = function(){
// tranfser-encode: chunk: 分块编码
return 'transfer-encoding' in req.headers || 'content-length' in req.headers
}
// hasOwnProperty 获取对象自有属性
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
// 读取 pkg.json
// check if the directory is a package.json dir
var packageMainCache = {};
function readPackage(requestPath) {
if (hasOwnProperty(packageMainCache, requestPath)) {
return packageMainCache[requestPath];
}
try {
var jsonPath = path.resolve(requestPath, 'package.json');
var json = fs.readFileSync(jsonPath, 'utf8');
} catch (e) {
return false;
}
try {
var pkg = packageMainCache[requestPath] = JSON.parse(json).main;
} catch (e) {
e.path = jsonPath;
e.message = 'Error parsing ' + jsonPath + ': ' + e.message;
throw e;
}
return pkg;
}
// require.js 源码
https://github.com/nodejs/node-v0.x-archive/blob/master/lib/module.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment