forked from cmd430/tv-movie-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.js
93 lines (83 loc) · 2.2 KB
/
util.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
const CronJob = require("cron").CronJob,
fs = require("fs"),
config = require("./config");
/* Makes the temporary directory. */
const makeTemp = () => {
if (!fs.existsSync(config.tempDir)) {
fs.mkdirSync(config.tempDir);
}
};
module.exports = {
makeTemp: makeTemp,
/* Error logger function. */
onError: (errorMessage) => {
fs.appendFile(config.tempDir + "/" + config.errorLog, errorMessage + "\n");
console.error(errorMessage);
return new Error(errorMessage);
},
/* Updates the 'lastUpdated' file. */
setlastUpdate: () => {
fs.writeFile(config.tempDir + "/" + config.updatedFile, JSON.stringify({
lastUpdated: Math.floor(new Date().getTime() / 1000)
}), (err) => {});
},
/* Updates the 'status' file. */
setStatus: (status) => {
fs.writeFile(config.tempDir + "/" + config.statusFile, JSON.stringify({
"status": status
}), (err) => {});
},
/*
* Function for resolving generators.
* Method from: https://www.youtube.com/watch?v=lil4YCCXRYc
*/
spawn: (generator) => {
return new Promise((resolve, reject) => {
let onResult = (lastPromiseResult) => {
let {
value,
done
} = generator.next(lastPromiseResult);
if (!done) {
value.then(onResult, reject)
} else {
resolve(value);
}
};
onResult();
});
},
/* Removes all the files in the temporary directory. */
resetTemp: (path = config.tempDir) => {
const files = fs.readdirSync(path);
files.forEach((file) => {
const stats = fs.statSync(path + "/" + file);
if (stats.isDirectory()) {
resetTemp(file);
} else if (stats.isFile()) {
fs.unlinkSync(path + "/" + file);
}
});
makeTemp();
},
/* Initiates the cronjob. */
initCron: (cronTime, job, doneFunction) => {
try {
const job = new CronJob({
cronTime: cronTime,
onTick: () => {
job;
},
onComplete: () => {
doneFunction;
},
start: true,
timeZone: "America/Los_Angeles"
});
console.log("Cron job started");
} catch (ex) {
util.onError("Cron pattern not valid");
}
job;
}
};