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?

WebエンジニアのためのCSVとバイナリ通信の基本技術まとめ

Posted at

1.CSV(Comma-Separated Values)

  • テキストベースの表形式データ
  • 各行 = レコード、各列 = カンマ区切りのフィールド
  • 改行・カンマ・クォートを含む場合のエスケープに注意
  • MIMEタイプ: text/csv
名前,年齢
"山田太郎",30
"佐藤, 花子","25"

2. MIME(Multipurpose Internet Mail Extensions)

  • データの「種類」を表す識別子
  • HTTPヘッダー Content-Type に指定することで、通信内容の意味を明確化

例:

種別 MIMEタイプ
CSV text/csv
JSON application/json
画像 image/png, image/jpeg
PDF application/pdf
汎用バイナリ application/octet-stream

3.HTTPとの関係

  • HTTPは通信プロトコル
  • 本文(body)にCSV、JSON、ArrayBufferなど様々な形式を送信可能
  • Content-Type ヘッダーがデータの種類を示す
Content-Type: text/csv
Content-Disposition: attachment; filename="data.csv"

4. Stream(ストリーム)

  • データを小さなチャンク(塊)に分けて逐次処理する仕組み
  • メモリ効率が良く、ファイル処理やネットワーク通信に適している

Node.js例:

const fs = require('fs');
const readable = fs.createReadStream('file.csv');
readable.on('data', chunk => console.log(chunk));

5. pipe(ストリームの接続)

  • Stream同士をつなぐためのメソッド
  • データを加工しながら流すことができる
readableStream
  .pipe(transformStream)
  .pipe(writableStream);

6. Blob(ブラウザでのバイナリデータ)

  • ブラウザ上で扱えるファイルデータ(バイナリの塊)
  • MIMEタイプ付きで生成でき、URL.createObjectURL()でダウンロード可能
const blob = new Blob(["名前,年齢\n太郎,30"], { type: "text/csv" });
const url = URL.createObjectURL(blob);

7. Buffer(Node.jsのバイナリデータ)

  • Node.jsにおける低レベルなバイナリデータの管理オブジェクト
  • ArrayBufferとの相互変換も可能
const buffer = Buffer.from("Hello, world!", "utf-8");
console.log(buffer.toString()); // Hello, world!

8. CSVをNode.jsで生成しダウンロード可能にする(バックエンド編)

◾ 必要なライブラリ

  • csv-stringify(npm)
  • express(Webサーバー)

◾ 実装例

npm install express csv-stringify
const express = require('express');
const { stringify } = require('csv-stringify');
const app = express();

app.get('/download', (req, res) => {
  res.setHeader('Content-Type', 'text/csv');
  res.setHeader('Content-Disposition', 'attachment; filename="data.csv"');

  const data = [
    ['名前', '年齢'],
    ['山田太郎', 30],
    ['佐藤花子', 25]
  ];

  stringify(data).pipe(res);  // stream + pipeで直接レスポンスに出力
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

9. フロントエンドでCSVを生成しダウンロード可能にする(クライアント編)

◾ BlobとURLを使った例

<button id="download">CSVダウンロード</button>

<script>
document.getElementById('download').addEventListener('click', () => {
  const data = [
    ['名前', '年齢'],
    ['山田太郎', 30],
    ['佐藤花子', 25]
  ];

  const csv = data.map(row => row.join(',')).join('\n');

  // UTF-8 BOM付きでExcel文字化け防止
  const bom = '\uFEFF';
  const blob = new Blob([bom + csv], { type: 'text/csv' });
  const url = URL.createObjectURL(blob);

  const a = document.createElement('a');
  a.href = url;
  a.download = 'data.csv';
  a.click();

  URL.revokeObjectURL(url); // メモリ解放
});
</script>

これでバックエンド・フロントエンドの両方でCSVを動的に生成し、ユーザーにダウンロードさせる処理が可能になります。

技術のつながり(まとめ)

概念 役割・用途
CSV データフォーマット(表形式)
MIME データの種類をHTTPなどで明示
HTTP 通信プロトコル。ボディに様々なデータを送受信可能
Stream データを効率よく逐次処理
pipe ストリーム同士の連携
Blob フロントエンドでのバイナリデータ表現
Buffer Node.jsでのバイナリデータ表現

✅ 参考リンク

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?