Skip to content

Instantly share code, notes, and snippets.

@mauricedb
Created April 9, 2018 18:44
Show Gist options
  • Save mauricedb/8defe96acbb28f4848a9da6c2ffd662e to your computer and use it in GitHub Desktop.
Save mauricedb/8defe96acbb28f4848a9da6c2ffd662e to your computer and use it in GitHub Desktop.
Local shortcut for HTTP request done before
const fs = require('fs');
const util = require('util');
const crypto = require('crypto');
const mkdrip = require('mkdirp');
const fetch = require('node-fetch');
const exists = util.promisify(fs.exists);
const readFile = util.promisify(fs.readFile);
module.exports = url => {
const hash = crypto
.createHash('md5')
.update(url)
.digest('hex');
const fileName = `c:/temp/data/${hash}.json`;
return exists(fileName).then(async exists => {
if (exists) {
const data = JSON.parse(await readFile(fileName, 'utf8'));
return data;
} else {
const rsp = await fetch(url);
const data = await rsp.json();
mkdrip('c:/temp/data', err => {
if (err) throw err;
fs.writeFile(fileName, JSON.stringify(data, null, 2), err => {
if (err) console.error(err);
});
});
return data;
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment