Skip to content

Instantly share code, notes, and snippets.

@mbostock mbostock/get.js
Created Jul 11, 2012

Embed
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 = [];
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);
}
}
@maxogden

This comment has been minimized.

Copy link

commented Jul 11, 2012

protips: npm install request and npm install filed

@mbostock

This comment has been minimized.

Copy link
Owner Author

commented Jul 11, 2012

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

This comment has been minimized.

Copy link

commented Jul 11, 2012

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

@maxogden

This comment has been minimized.

Copy link

commented Jul 11, 2012

@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
You can’t perform that action at this time.