Should I be using something different than fs?
Yes. The fs
module is meant for interacting with the machine's local file systems, rather than handling network communication such as HTTP requests and responses.
You can use the http
module, specifically http.get()
, to request a file from an HTTP server:
http.get('http://www.mydomain.com/uploads/docs/doc.doc', function (res) {
// process the response, `res`, as desired
if (res.statusCode === 200) {
// Example, piping the response to a file on disk:
res.pipe(fs.createWriteStream(__dirname + '/doc.doc'));
} else {
console.error('The address is unavailable. (%d)', res.statusCode);
}
});
res
will be an http.IncomingMessage
, which are stream.Readable
s.