TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Monkey Patching in Node.js

16 pointsby sekalmost 12 years ago

3 comments

joshguthriealmost 12 years ago
Express offers something similar to organize&#x2F;simplify your routing:<p><pre><code> var express = require(&#x27;express&#x27;); var appRoot = express(); var appFoobar = express(); appFoobar.get(&#x27;&#x2F;bar&#x27;, function (req, res) { res.end(&#x27;&#x2F;foo&#x2F;bar&#x27;); }); appRoot.use(&#x27;&#x2F;foo&#x27;, appFoobar); appRoot.listen(process.env.PORT); $ curl localhost:3000&#x2F;foo&#x2F;bar &#x2F;foo&#x2F;bar $ </code></pre> As for &quot;monkey patching&quot;, overwriting methods is often a bad idea. It may be better to use a new method to call upon the old one:<p><pre><code> Hapi.Server.prototype.routeAPI = function (routes) { if (!Array.isArray(routes)) routes = [ routes ]; routes = routes.map(function (route) { route.path = &#x27;&#x2F;api&#x27; + route.path; return route; }); return this.route(routes); } </code></pre> Like nadadiv said, you could even have gone without recreating a Server() instance each time.
评论 #6155207 未加载
评论 #6155154 未加载
amasadalmost 12 years ago
FYI - no need for underscore if you&#x27;re only targeting node.js. You can use Array.isArray and routes.map instead of _.isArray and _.map
nadavivalmost 12 years ago
&gt; server.route = new Hapi.Server().route;<p>Seems wasteful to create an instance only to get a property, when you can just use `Hapi.Server.prototype.route` instead
评论 #6155140 未加载
评论 #6155134 未加载