Created
July 11, 2012 18:45
Read File or HTTP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require("fs"), | |
http = require("http"); | |
function get(url, callback) { | |
if (/^http:/.test(url)) { | |
http.get(url, function(response) { | |
var body = []; | |
response | |
.on("data", function(data) { body.push(data); }) | |
.on("end", function() { callback(null, body.join("")); }) | |
.setEncoding("utf8"); | |
}).on("error", function(error) { | |
callback(error, null); | |
}); | |
} else { | |
fs.readFile(url, "utf8", callback); | |
} | |
} |
I've done this before and ended up going back in and supporting /^https?:/
too.
@mbostock fair points, but you should check out http://nodejs.org/docs/latest/api/stream.html. since you're not returning the streams here you lose a lot of composability later
you can also use the url
module to parse out the protocol
of a uri instead of regexin
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
protips:
npm install request
andnpm install filed