package.jsonを作成
npm init -y
必要なパッケージをimport
npm install express csv-writer
npm install --save-dev typescript @types/node @types/express ts-node
tsconfig.jsonの作成
tsconfig.json
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true
}
}
サーバーファイルを作成
src/index.ts
import express from "express";
import { createObjectCsvWriter } from "csv-writer";
import path from "path";
import fs from "fs";
const app = express();
const port = 3100;
app.get("/download-csv", async (req, res) => {
try {
const csvFilePath = path.join(__dirname, "output.csv");
const csvWriter = createObjectCsvWriter({
path: csvFilePath,
header: [
{ id: "id", title: "ID" },
{ id: "name", title: "Name" },
{ id: "email", title: "Email" },
],
});
const records = [
{ id: 1, name: "John Doe", email: "john.doe@example.com" },
{ id: 2, name: "Jane Doe", email: "jane.doe@example.com" },
];
await csvWriter.writeRecords(records);
res.download(csvFilePath, "output.csv", (err) => {
if (err) {
console.error("Error downloading the file:", err);
res.status(500).send("Error downloading the file");
} else {
fs.unlinkSync(csvFilePath); // ダウンロード後にファイルを削除
}
});
} catch (error) {
console.error("Error processing the request:", error);
res.status(503).send("Service Unavailable");
}
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
サーバ起動
npx ts-node src/index.ts