cvt / app.js
Reaperxxxx's picture
Create app.js
0e590ca verified
Raw
History Blame Contribute Delete
2.15 kB
const express = require("express");
const axios = require("axios");
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const ffmpeg = require("fluent-ffmpeg"); // will use system ffmpeg
const app = express();
const PORT = 7860;
// Ensure output folder exists
const outputDir = path.join(__dirname, "output");
if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir);
// Serve converted files
app.use("/output", express.static(outputDir));
// Generate random hex filename
function randomHex(len = 16) {
return crypto.randomBytes(len).toString("hex");
}
app.get("/convert", async (req, res) => {
try {
const { url } = req.query;
if (!url) return res.status(400).json({ error: "Missing audio URL" });
const m4aPath = path.join(__dirname, `${randomHex()}.m4a`);
const mp3Path = path.join(outputDir, `${randomHex()}.mp3`);
// Download the m4a file
const response = await axios({
method: "GET",
url,
responseType: "stream"
});
const writer = fs.createWriteStream(m4aPath);
response.data.pipe(writer);
writer.on("finish", () => {
ffmpeg(m4aPath)
.toFormat("mp3")
.on("end", () => {
fs.unlinkSync(m4aPath); // cleanup temp file
const fileUrl = `${req.protocol}://${req.get("host")}/output/${path.basename(mp3Path)}`;
res.json({ mp3: fileUrl });
})
.on("error", err => {
console.error("FFmpeg error:", err);
res.status(500).json({ error: "Conversion failed" });
})
.save(mp3Path);
});
writer.on("error", err => {
console.error("Download error:", err);
res.status(500).json({ error: "Failed to download file" });
});
} catch (err) {
console.error(err);
res.status(500).json({ error: "Internal server error" });
}
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});