Team Ai
Apppublic

Ratankumar10/code-execution-engine

sourceHugging Faceupdated 8mo agoView on Hugging Face
0likes
file.util.js65 linesDownload Raw Back to utils
1// ─── File Utility ────────────────────────────2// Manages temp directories for each execution3 4const fs = require("fs").promises;5const path = require("path");6const { v4: uuidv4 } = require("uuid");7const config = require("../config");8 9/**10 * Ensure directory exists (mkdir -p)11 */12async function ensureDir(dirPath) {13  await fs.mkdir(dirPath, { recursive: true });14}15 16/**17 * Create a unique working directory for an execution.18 * Structure:19 *   /tmp/judge/<uuid>/20 *     code/          ← source files go here21 *     input.txt      ← stdin22 *     output.txt     ← stdout (written by runner)23 *     stderr.txt     ← stderr (written by runner)24 *     meta.txt       ← metadata (written by runner)25 */26async function createWorkDir() {27  const id = uuidv4();28  const workDir = path.join(config.TEMP_DIR, id);29  await ensureDir(workDir);30  await ensureDir(path.join(workDir, "code"));31  return workDir;32}33 34/**35 * Write content to a file (creating parent dirs if needed)36 */37async function writeFile(filePath, content) {38  await ensureDir(path.dirname(filePath));39  await fs.writeFile(filePath, content, "utf8");40}41 42/**43 * Read file content (returns empty string on failure)44 */45async function readFile(filePath) {46  try {47    return await fs.readFile(filePath, "utf8");48  } catch {49    return "";50  }51}52 53/**54 * Recursively delete a directory and its contents55 */56async function cleanup(dirPath) {57  try {58    await fs.rm(dirPath, { recursive: true, force: true });59  } catch {60    // Ignore cleanup errors — temp dirs will be cleaned eventually61  }62}63 64module.exports = { ensureDir, createWorkDir, writeFile, readFile, cleanup };65