Skip to content

Instantly share code, notes, and snippets.

Created July 11, 2012 18:45
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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 = [];
.on("data", function(data) { body.push(data); })
.on("end", function() { callback(null, body.join("")); })
}).on("error", function(error) {
callback(error, null);
} else {
fs.readFile(url, "utf8", callback);
Copy link

protips: npm install request and npm install filed

Copy link

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.)

Copy link

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

Copy link

@mbostock fair points, but you should check out 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