-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
75 lines (68 loc) · 2.53 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const fs = require("fs");
const moment = require("moment");
const pdf = require("pdf-parse");
/**
* Returns a string representation of the week of a given date.
* @param {Date} date - The date.
* @return {string} - The string representation of the week (e.g., "Oct 03 - Oct 09, 2023").
*/
function getWeekString(date) {
const startOfWeek = moment(date).startOf('week').day(0); // Set week start on Sunday
const endOfWeek = moment(date).endOf('week').day(6); // Set week end on Saturday
return `${startOfWeek.format('MMM DD')} - ${endOfWeek.format('MMM DD, YYYY')}`;
}
/**
* Helper function to parse date strings from the PDF into Date objects.
* @param {string} dateStr - The date string from the PDF.
* @return {Date} - A JavaScript Date object.
*/
function parseDate(dateStr) {
const formattedDateStr = dateStr.replace(' at ', ' ').replace(/(AM|PM)/, ' $1');
return new Date(moment(formattedDateStr, 'MM/DD/YYYY hh:mm A').toDate());
}
/**
* Helper function to format date strings from the PDF into a more readable format.
* @param {string|object} dateStr - The parsed date object from the PDF, or a string ('Never')
*/
function formatDate(dateStr) {
// console.log('dateStr', dateStr, typeof dateStr);
if (typeof dateStr === 'object') {
return dateStr.toString().replace(' GMT-0800 (Pacific Standard Time)', '');
}
return dateStr;
}
/**
* Writes the provided data to a file at the provided file path, and logs a
* confirmation message to the console.
*
* @param {string} filePath - The path to the output file.
* @param {string} data - The data to write to the file.
*/
function writeFile(filePath, data) {
try {
fs.writeFileSync(filePath, data);
// console.log(`File written to: ${filePath}`);
} catch (error) {
console.error(`Failed to write to ${filePath}:`, error);
}
}
/**
* Parses the PDF file at the specified file path.
* @param {string} filePath - The path to the PDF file.
* @return {Promise<string>} - A promise that resolves to the text content of the PDF file.
*/
async function parsePdf(filePath) {
try {
const dataBuffer = fs.readFileSync(filePath);
const data = await pdf(dataBuffer);
return data.text;
} catch (error) {
console.error(`Failed to parse PDF at ${filePath}:`, error);
throw error; // Re-throw the error to be caught by the calling function
}
}
exports.getWeekString = getWeekString;
exports.parsePdf = parsePdf;
exports.parseDate = parseDate;
exports.formatDate = formatDate;
exports.writeFile = writeFile;