Created
July 11, 2012 18:45
-
-
Save mbostock/3092303 to your computer and use it in GitHub Desktop.
Read File or HTTP
This file contains 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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 theprotocol
of a uri instead of regexin