Changed the io helpers to use promises

This commit is contained in:
Lee 2022-11-15 03:33:50 +00:00
parent 006ee69039
commit 9eca5f3b26
No known key found for this signature in database
GPG Key ID: 6EA25896ECCB3121

@ -16,6 +16,7 @@ export function exists(path) {
if (existsCache.has(path)) { if (existsCache.has(path)) {
return existsCache.get(path); return existsCache.get(path);
} }
// eslint-disable-next-line security/detect-non-literal-fs-filename
const exists = fs.existsSync(path); const exists = fs.existsSync(path);
existsCache.set(path, exists); existsCache.set(path, exists);
return exists; return exists;
@ -28,23 +29,29 @@ export function exists(path) {
* @param {Buffer} bytes The bytes of the file * @param {Buffer} bytes The bytes of the file
*/ */
export function createFileIO(dir, fileName, bytes) { export function createFileIO(dir, fileName, bytes) {
return new Promise(async (resolve, reject) => {
if (!exists(dir)) { if (!exists(dir)) {
fs.mkdirSync(dir, { recursive: true }); // eslint-disable-next-line security/detect-non-literal-fs-filename
try {
await fs.promises.mkdir(dir, { recursive: true }); // Create any missing directories
} catch (err) {
console.log(err);
return reject(err);
}
} }
const fileLocation = dir + path.sep + fileName; const fileLocation = dir + path.sep + fileName;
fs.writeFile( try {
fileLocation, // eslint-disable-next-line security/detect-non-literal-fs-filename
bytes, await fs.promises.writeFile(fileLocation, bytes); // Write the file to disk
{ resolve();
encoding: "utf-8", } catch (err) {
},
(err) => {
if (err) {
console.log(err); console.log(err);
// eslint-disable-next-line security/detect-non-literal-fs-filename
await fs.promises.unlink(fileLocation); // Delete the file
return reject(err);
} }
} });
);
} }
/** /**
@ -54,12 +61,6 @@ export function createFileIO(dir, fileName, bytes) {
* @return The file * @return The file
*/ */
export function readFileIO(path) { export function readFileIO(path) {
return new Promise((resolve, reject) => { // eslint-disable-next-line security/detect-non-literal-fs-filename
fs.readFile(path, (err, data) => { return fs.createReadStream(path);
if (err) {
return reject(err);
}
return resolve(data);
});
});
} }