Skip to content

Instantly share code, notes, and snippets.

@cobalamin
Created May 20, 2015 08:27
Show Gist options
  • Save cobalamin/5288917a1ce96d4da5ec to your computer and use it in GitHub Desktop.
Save cobalamin/5288917a1ce96d4da5ec to your computer and use it in GitHub Desktop.
Fetch all available/listed NASA images of the day. Can be run through cron, executed by node.
var rss_url = 'http://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss';
var directory = '?';
var FeedParser = require('feedparser'),
request = require('request'),
fs = require('fs'),
path = require('path');
var feedparser = new FeedParser(),
req = request(rss_url);
req.on('error', function(err) {
throw err;
});
req.pipe(feedparser);
feedparser.on('error', function(err) {
throw err;
});
feedparser.on('readable', function() {
var stream = this,
meta = this.meta,
item;
while (item = stream.read()) {
var title = item.title,
date = new Date(item.pubDate),
enclosures = item.enclosures;
if(enclosures != null) {
enclosures.forEach(function(enc, i) {
var enc_url = enc.url,
fetch_req = request(enc_url),
full_title = title + ' (#' + i + ')';
fetch_req.on('error', function(err) {
console.log('Could not fetch ' + full_title + ': ' + err);
});
fetch_req.on('response', function(res) {
var datestring = date.toISOString().substring(0, 10);
var original_filename = path.basename(enc_url);
var filename = datestring + '_' + original_filename;
var full_filename = path.join(directory, filename);
if(fs.existsSync(full_filename)) {
console.log("Didn't fetch " + full_title + "; the image did already exist");
}
else {
var writeStream = fs.createWriteStream(full_filename);
fetch_req.pipe(writeStream);
fetch_req.on('end', function() {
console.log('Fetched ' + full_title);
});
}
});
});
}
}
});
{
"name": "nasa-image-of-the-day",
"version": "1.0.0",
"description": "",
"main": "index.js",
"author": "Simon Welker",
"license": "MIT",
"dependencies": {
"feedparser": "^1.0.1",
"request": "^2.55.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment