Untitled

 avatar
unknown
plain_text
a year ago
1.1 kB
2
Indexable
const { exec } = require("child_process");
const fs = require("fs");
const path = require("path");
const { v4: uuidv4 } = require("uuid");

const executeCPP = (code, input) => {
  return new Promise((resolve, reject) => {
    const jobId = uuidv4();
    const inputFilePath = path.join(__dirname, `${jobId}.txt`);
    const outputFilePath = path.join(__dirname, `${jobId}.out`);
    const codeFilePath = path.join(__dirname, `${jobId}.cpp`);

    fs.writeFileSync(inputFilePath, input);
    fs.writeFileSync(codeFilePath, code);

    exec(`g++ ${codeFilePath} -o ${jobId} && ./${jobId} < ${inputFilePath} > ${outputFilePath}`, (error, stdout, stderr) => {
      if (error) {
        return reject({ error, stderr });
      }

      const output = fs.readFileSync(outputFilePath, "utf-8");
      resolve({ stdout: output });
      
      // Clean up files
      fs.unlinkSync(inputFilePath);
      fs.unlinkSync(outputFilePath);
      fs.unlinkSync(codeFilePath);
      fs.unlinkSync(jobId);
    });
  });
};

module.exports = { executeCPP };
Editor is loading...
Leave a Comment