kanji-sheets/jishoScrape/index.js

74 lines
2.4 KiB
JavaScript
Raw Normal View History

const fs = require('fs');
2020-05-25 23:03:19 +02:00
/* Import local files */
2020-05-27 17:28:01 +02:00
const {fetchKanjiFromTxt, fetchJishoBufferData, fetchKanjiFromJisho} = require('./src/dataFetching.js');
const {getKanjiTexData} = require('./src/texConversion.js');
const {kanjiTable} = require('./src/kanjiTables.js');
2020-06-08 21:58:58 +02:00
function log(message, jlptLevel) {
2020-05-25 22:16:04 +02:00
const jlptLevelCaps = jlptLevel.toUpperCase();
2020-06-08 21:58:58 +02:00
console.log(`${jlptLevelCaps}: ${message}`);
}
2020-05-25 22:16:04 +02:00
2020-06-08 21:58:58 +02:00
/* Encapsulate main process in async function */
async function main(jlptLevel) {
2020-05-27 17:28:01 +02:00
2020-06-08 21:58:58 +02:00
const jishoResults = await fetchJishoResults(jlptLevel);
const kanjiArray = jishoResults.map(result => result.query);
2020-06-08 21:58:58 +02:00
log('Generating tex pages', jlptLevel);
2020-05-25 23:03:19 +02:00
const texData = getKanjiTexData(jishoResults);
2020-06-08 21:58:58 +02:00
log('Generating chapter table page', jlptLevel);
const resultTable = kanjiTable(kanjiArray);
let resultPage = '';
for (kanji of texData) {
resultPage+=`${kanji.kanjiPageHeader}
${kanji.kanjiMeaning ? kanji.kanjiMeaning : ''}
${kanji.kunyomi ? kanji.kunyomi : ''}
${kanji.onyomi ? kanji.onyomi : ''}
${kanji.kanjiRow}
\\newpage\n`;
}
2020-05-25 22:16:04 +02:00
fs.writeFile(`./data/tables/${jlptLevel}.tex`, resultTable, (err) => {if (err) console.error(err)});
fs.writeFile(`./data/pages/${jlptLevel}.tex`, resultPage, (err) => {if (err) console.error(err)});
}
2020-06-08 21:58:58 +02:00
/** Fetch data from buffer if available.
* Else fetch data from txt and jisho requests,
* and make buffer files
*/
async function fetchJishoResults(jlptLevel) {
const bufferFileExists = fs.existsSync(`./data/jisho/${jlptLevel}.json`);
if(bufferFileExists) {
log('Fetching Jisho data from buffer', jlptLevel)
return await fetchJishoBufferData(`./data/jisho/${jlptLevel}.json`);
} else {
log('Fetching data from Jisho and writing to buffer', jlptLevel)
return await fetchJishoDataAndWriteToBuffer(jlptLevel);
}
}
async function fetchJishoDataAndWriteToBuffer(jlptLevel) {
const kanjiArray = await fetchKanjiFromTxt(`./data/txt/${jlptLevel}.txt`);
const jishoResults = await fetchKanjiFromJisho(kanjiArray);
fs.writeFile(`./data/jisho/${jlptLevel}.json`, JSON.stringify(jishoResults, null, " "), (err) => {if (err) console.error(err)});
return jishoResults;
}
2020-05-25 23:03:19 +02:00
/* Handle args */
async function argWrapper() {
try {
if (!/n\d/.test(process.argv[2])) throw 'Input not valid';
await main(process.argv[2]);
} catch (error) {
console.error(error);
}
}
2020-05-25 23:03:19 +02:00
argWrapper();