Thursday 23 April 2020

Why I love duck-typing

When I am close to forget why I love node.js then a challenging task that would be impossible to do in any other language, reveals trivial on node/js.Today I was configuring a gulp pipeline that has to use an external library. Everything works fine except on watch mode, because the library starts an http server and if I try to run it again I will get a port in use error. Such lib doesn't expose the created server at all, so what I did? You said it, duck-typing!! I mock the http create server function in just 3 lines of code:javascript const http = require('http'); const _creates = http.createServer; let twServer; http.createServer = function createServerMock() { twServer = _creates.apply(http,arguments) return twServer }Then my gulp tasks become trivial!!!``` function stopAnyRunningServer(cb) { if(!twServer) return cb() twServer.close(cb) }function serve(cb) { externallibrarycommand('--server','8087') cb() } ```No need to spawn processes, no need to use nodemon or any external library, just plain node + gulp

Submitted April 23, 2020 at 07:33PM by danielo515

No comments:

Post a Comment