Skip to content

Instantly share code, notes, and snippets.

@mbostock
Created July 11, 2012 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbostock/3092303 to your computer and use it in GitHub Desktop.
Save mbostock/3092303 to your computer and use it in GitHub Desktop.
Read File or HTTP
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);
}
}
@max-mapper
Copy link

protips: npm install request and npm install filed

@mbostock
Copy link
Author

I found request, but it didn't support local files; and filed looks like the inverse. I want something that handles both. (And given that it's only 18 lines of code, I don't see the harm.)

@RandomEtc
Copy link

I've done this before and ended up going back in and supporting /^https?:/ too.

@max-mapper
Copy link

@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