UNPKG

@sidekick-coder/db

Version:

Cli Tool to manipulate data from diferent sources

128 lines (124 loc) 3.29 kB
import cp from 'child_process'; import fs from 'fs'; import os from 'os'; import { join } from 'path'; // src/core/filesystem/createFsNode.ts // src/utils/tryCatch.ts async function tryCatch(tryer) { try { const result = await tryer(); return [result, null]; } catch (error) { return [null, error]; } } tryCatch.sync = function(tryer) { try { const result = tryer(); return [result, null]; } catch (error) { return [null, error]; } }; function createFsNode() { const exists = async (path) => { const [, error] = await tryCatch(() => fs.promises.access(path)); return error ? false : true; }; const existsSync = (path) => { const [, error] = tryCatch.sync(() => fs.accessSync(path)); return error ? false : true; }; const read = async (path) => { const [content, error] = await tryCatch(() => fs.promises.readFile(path)); if (error) { return null; } return new Uint8Array(content); }; const readSync = (path) => { const [content, error] = tryCatch.sync(() => fs.readFileSync(path)); if (error) { return null; } return new Uint8Array(content); }; const readdir = async (path) => { const [files, error] = await tryCatch(() => fs.promises.readdir(path)); return error ? [] : files; }; const readdirSync = (path) => { const [files, error] = tryCatch.sync(() => fs.readdirSync(path)); return error ? [] : files; }; const write = async (path, content) => { const [, error] = await tryCatch(() => fs.promises.writeFile(path, content)); if (error) { throw error; } }; const writeSync = (path, content) => { const [, error] = tryCatch.sync(() => fs.writeFileSync(path, content)); if (error) { throw error; } }; const mkdir = async (path) => { const [, error] = await tryCatch(() => fs.promises.mkdir(path)); if (error) { throw error; } }; const mkdirSync = (path) => { const [, error] = tryCatch.sync(() => fs.mkdirSync(path)); if (error) { throw error; } }; const remove = async (path) => { const [, error] = await tryCatch(() => fs.promises.rm(path, { recursive: true })); if (error) { throw error; } }; const removeSync = (path) => { const [, error] = tryCatch.sync(() => fs.rmSync(path, { recursive: true })); if (error) { throw error; } }; const removeAt = async (path, milliseconds) => { if (os.platform() === "win32") { const script = ` Set objShell = CreateObject("WScript.Shell") objShell.Run "cmd /c timeout /t ${milliseconds / 1e3} && del /f /q ${path}", 0, True `; const key = Math.random().toString(36).substring(7); const tempScriptPath = join(os.tmpdir(), `db-delete-file-${key}.vbs`); fs.writeFileSync(tempScriptPath, script); const child = cp.spawn("cscript.exe", [tempScriptPath], { detached: true, stdio: "ignore" }); child.unref(); return true; } return false; }; return { exists, existsSync, read, readSync, readdir, readdirSync, write, writeSync, mkdir, mkdirSync, remove, removeSync, removeAt }; } export { createFsNode };