Skip to content

Instantly share code, notes, and snippets.

@joelrbrandt
Last active August 29, 2015 14:08
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 joelrbrandt/91cd75e65f49d12d297a to your computer and use it in GitHub Desktop.
Save joelrbrandt/91cd75e65f49d12d297a to your computer and use it in GitHub Desktop.
getting the contents of a url as a string using node
var getURL = function (url, cb) {
var http = require("http");
var result = "",
finished = false;
var finishedHandler = function (err, val) {
if (!finished) {
finished = true;
cb(err, val);
}
};
var responseHandler = function (res) {
if (res.statusCode !== 200) {
finishedHandler(new Error("HTTP request status code " + res.statusCode));
res.resume();
return;
}
res.on("readable", function () {
var b = res.read();
result += b.toString();
});
res.on("end", function() {
finishedHandler(null, result);
});
res.on("error", function(err) {
finishedHandler(err);
});
};
var req = http.get(url, responseHandler);
req.on("error", finishedHandler);
};
// "path" should be an absolute path on the filesystem, otherwise
// who knows what it will be relative to in CEP land
var downloadURLToFile = function (url, path, cb) {
var http = require("http"),
fs = require("fs");
var finished = false;
var finishedHandler = function (err) {
if (!finished) {
finished = true;
cb(err);
}
};
var responseHandler = function (res) {
if (res.statusCode !== 200) {
finishedHandler(new Error("HTTP request status code " + res.statusCode));
res.resume();
return;
}
var ws = fs.createWriteStream(path);
ws.on("error", function (err) {
ws.end();
finishedHandler(err);
});
res.on("error", function (err) {
ws.end();
finishedHandler(err);
});
res.pipe(ws);
ws.on("finish", finishedHandler);
};
var req = http.get(url, responseHandler);
req.on("error", finishedHandler);
};
getURL("http://localhost:8080/", function (err, text) {
if (err) {
console.log("There was an error getting the URL: " + err);
} else {
console.log(text);
}
});
var movieURL = "http://localhost:8080/foo.m4a";
var localPath = "/Users/jbrandt/Desktop/foo.m4a";
downloadURLToFile(movieURL, localPath, function (err, text) {
if (err) {
console.log("There was an error downloading the URL: " + err);
} else {
console.log("done downloading!");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment