Files
parcer/server/src/workflow-management/storage.ts

84 lines
2.2 KiB
TypeScript
Raw Normal View History

2024-06-08 20:55:58 +05:30
/**
* A group of functions for storing recordings on the file system.
* Functions are asynchronous to unload the server from heavy file system operations.
*/
import fs from 'fs';
import * as path from "path";
2024-06-08 20:56:15 +05:30
/**
* Reads a file from path and returns its content as a string.
* @param path The path to the file.
* @returns {Promise<string>}
* @category WorkflowManagement-Storage
*/
2024-06-08 20:55:58 +05:30
export const readFile = (path: string): Promise<string> => {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
};
2024-06-08 20:58:17 +05:30
/**
* Writes a string to a file. If the file already exists, it is overwritten.
* @param path The path to the file.
* @param data The data to write to the file.
* @returns {Promise<void>}
* @category WorkflowManagement-Storage
*/
2024-06-08 20:58:07 +05:30
export const saveFile = (path: string, data: string): Promise<void> => {
return new Promise((resolve, reject) => {
fs.writeFile(path, data, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
2024-06-08 20:59:00 +05:30
/**
* Deletes a file from the file system.
* @param path The path to the file.
* @returns {Promise<void>}
* @category WorkflowManagement-Storage
*/
2024-06-08 20:58:50 +05:30
export const deleteFile = (path: string): Promise<void> => {
return new Promise((resolve, reject) => {
fs.unlink(path, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
/**
* A helper function to apply a callback to the all resolved
* promises made out of an array of the items.
* @param items An array of items.
* @param block The function to call for each item after the promise for it was resolved.
* @returns {Promise<any[]>}
* @category WorkflowManagement-Storage
*/
function promiseAllP(items: any, block: any) {
let promises: any = [];
items.forEach(function(item : any, index: number) {
promises.push( function(item,i) {
return new Promise(function(resolve, reject) {
// @ts-ignore
return block.apply(this,[item,index,resolve,reject]);
});
}(item,index))
});
return Promise.all(promises);
}
2024-06-08 20:58:07 +05:30