Skip to content

Instantly share code, notes, and snippets.

@hcgatewood
Last active December 23, 2019 08:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hcgatewood/10924e3778e30773b7429707adf5c07e to your computer and use it in GitHub Desktop.
Save hcgatewood/10924e3778e30773b7429707adf5c07e to your computer and use it in GitHub Desktop.
Pull a random word and definition from the Jargon File
// NOTE:
// Must have xray installed.
// Use `npm init -y && npm install -S x-ray` in an empty directory.
// Here's the link for npm: https://docs.npmjs.com/getting-started/installing-node
// NOTE:
// Here's the url of the Jargon File: http://www.catb.org/jargon/html/
'use strict';
const fs = require('fs');
const path = require('path');
const Xray = require('x-ray');
const xray = Xray();
const homeUrl = 'http://www.catb.org/jargon/html/go01.html';
const outputFilename = path.join(__dirname, 'output.txt');
function getTerm(callback) {
if (! callback) {
throw new Error('No callback passed');
}
console.log('Searching...');
xray(homeUrl, ['dd dl dt a@href'])( (err, urls) => {
if (err) console.error(err);
const chosenUrl = urls[Math.floor(Math.random() * urls.length)];
xray(chosenUrl, ['dd'])( (err, definitions) => {
if (err) console.error(err);
const definition = definitions.join('\n\n').trim();
xray(chosenUrl, '.navheader table tr th')( (err, title) => {
if (err) console.error(err);
return callback(title, definition);
});
});
});
}
function standardizeLineLength(string, length) {
string = string.replace(/\s+/g, ' ');
string = string.replace('\n', '');
const arr = string.split('');
const lines = [];
let start = 0;
let end = length;
while (true) {
if (end > arr.length) {
lines.push(arr.slice(start).join(''));
break;
}
const line = arr.slice(start, end);
const eol = line.lastIndexOf(' ');
if (eol === -1) eol = length;
lines.push(arr.slice(start, start + eol).join(''));
start += eol + 1;
end += eol + 1;
}
return lines.join('\n');
}
function main() {
getTerm( (title, definition) => {
const prettierDefinition = standardizeLineLength(definition, 75);
const fullMsg = title.toUpperCase() + ':\n\n' + prettierDefinition;
if (fullMsg.length > 300) main();
fs.writeFile(outputFilename, fullMsg, (err) => {
if (err) console.error(err);
})
});
}
main()
@hcgatewood
Copy link
Author

hcgatewood commented Jul 29, 2016

Can be used e.g. to set a cron job for updating your terminal's message of the day.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment