You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
36 lines
928 B
36 lines
928 B
/** @module file */
|
|
/// <reference path="result.js" />
|
|
import { ERROR, OK } from "./result.js";
|
|
import { readFile as readF, writeFile as writeF } from "fs/promises";
|
|
|
|
const FILE_READ_ERROR_MESSAGE = "Error reading file from disk";
|
|
const FILE_WRITE_ERROR_MESSAGE = "Error writing file to disk";
|
|
|
|
/**
|
|
* Try to read file from pathname
|
|
* @returns {Result<String>} result of reading file
|
|
*/
|
|
async function readFile(filePath) {
|
|
try {
|
|
const data = await readF(filePath, "utf8");
|
|
return [OK, data];
|
|
} catch (err) {
|
|
return [ERROR, `${FILE_READ_ERROR_MESSAGE}: ${err}`];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Try to write file to disk
|
|
* @returns {Result<String>} result of writing file
|
|
*/
|
|
async function writeFile(filename, content) {
|
|
try {
|
|
await writeF(filename, content);
|
|
return [OK, `File ${filename} created`];
|
|
} catch (err) {
|
|
return [ERROR, `${FILE_WRITE_ERROR_MESSAGE}: ${err}`];
|
|
}
|
|
}
|
|
|
|
export { readFile, writeFile };
|