0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Node.js】CSVファイルをダウンロードするAPIを構築

Posted at

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?