import fs from "fs"; import path from "path"; // import nextConnect from 'next-connect'; // import { sendFile } from 'next/dist/server/send-file'; import formidable from "formidable"; import { spawn } from "child_process"; export const config = { api: { bodyParser: false, }, }; export default async function (req, res) { const form = new formidable.IncomingForm(); try { form.parse(req, async (err, fields, files) => { if (err) { return res.status(400).json({ message: err.message }); } console.log('doing the saving') const { filepath, originalFilename } = files.file; const dateNow = Date.now() const newFilename = `${Date.now()}-${originalFilename}`; const newPath = path.join( process.cwd(), "public", "uploads", newFilename ); console.log('i tried so hart') const readStream = fs.createReadStream(filepath); const writeStream = fs.createWriteStream(newPath); readStream.on('error', function(err) { console.error('Error while reading file.', err); res.status(500).send('Error while uploading file.'); }); writeStream.on('error', function(err) { console.error('Error while writing file.', err); res.status(500).send('Error while uploading file.'); }); writeStream.on('finish', function() { console.log('File copied successfully'); let dataToSend; python.stdout.on("data", function (data) { console.log("Pipe data from python script ..."); dataToSend = data.toString(); console.log(dataToSend); }); python.stderr.on("data", (data) => { console.error(`stderr: ${data}`); res.send("Py Error: " + data); }); // in close event we are sure that stream from child process is closed python.on("close", (code) => { console.log(`child process close all stdio with code ${code}`); // send data to browser console.log(dataToSend); console.log("done"); try { // const handler = nextConnect(); // handler.get(async (req, res) => { const filename = newFilename; // get the filename from the query string const filePath = path.join(process.cwd(), 'public', 'uploads', filename); console.log(newFilename, filename, filePath, dataToSend) res.status(200).send({ filename: newFilename, filepath:filePath, data: dataToSend }); // sendFile(req, filePath); // send the file as a response // }); } catch (e) { console.log("child process end"); } }); }); readStream.pipe(writeStream); console.log('and got so far') let fileName = Math.floor(Math.random() * 9999) + 1000; console.log('starting the engines', newPath) const python = spawn("python3", ["cross.py", 50, newPath]); console.log('oui') // return res.status(200).json({ message: "File uploaded successfully" }); }); } catch (err) { console.log("err: ", err) return res.status(500).json({ message: err.message }); } }