1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.jsでCSVを読み込んでDBに保存する

Last updated at Posted at 2019-06-09

はじめに

Node.jsでCSVを読み込んでDBに保存するサンプルコードを作成しました。
コードの解説等はありませんので、あしからず。

前提条件

事前に以下をインストールしておいてください。

  • nodejs
  • yarn
  • sqlite3

実際に試した環境のバージョンはとおりです。

$ node --version
v12.4.0
$ yarn --version
1.16.0
$ sqlite3 --version
3.16.0 2016-11-04 19:09:39 0e5ffd9123d6d2d2b8f3701e8a73cc98a3a7ff5f

環境構築

$ mkdir sample && cd sample
$ yarn init -y
$ yarn add csv sequelize sqlite3

DB作成

$ sqlite3 ./sqlite3.db
sqlite> CREATE TABLE users(id integer primary key autoincrement, name text, email text);

テストデータ作成

$ cat <<EOF >> ./test.csv
yamada,s-yamada@sample.com
hayashi,y-hayashi@sample.com
tanaka,t-tanaka@sample.com
EOF

ソースコード

以下の内容を index.mjs というファイル名で保存する。

index.mjs
"use strict;"

import csvparse from 'csv-parse';
import fs from 'fs';
import Sequelize from "sequelize";
import transform from 'stream-transform';

const db = new Sequelize(
	'database', '', '', {
		dialect: 'sqlite',
		storage: './sqlite3.db',
	}
);

const User = db.define(
	"user", {
		name: Sequelize.STRING,
		email: Sequelize.STRING
	}, { timestamps: false }
);

const source = fs.createReadStream('test.csv');

const csvParser = csvparse({ columns: false });

const dataRegister = transform(async (record, callback) => {
	const user = {
		name: record[0].toUpperCase(),
		email: record[1]
	};
	await User.create(user);
	callback(null, user);
}, { parallel: 5 });

const resultLogger = async () => {
	const users = await User.findAll();
	console.log("[result]");
	for (let user of users) {
		console.log(JSON.stringify(user));
	}
};

db.transaction(async (t) => {
	await User.destroy({ where: {}, truncate: true });
	source.pipe(csvParser).pipe(dataRegister).on('finish', resultLogger);
});

実行

$ node --experimental-modules index.mjs
(node:58762) ExperimentalWarning: The ESM module loader is experimental.
Executing (7d95a3db-c374-4ca5-9ae8-21f4cc263d54): BEGIN DEFERRED TRANSACTION;
Executing (default): DELETE FROM `users`
Executing (7d95a3db-c374-4ca5-9ae8-21f4cc263d54): COMMIT;
Executing (default): SELECT `id`, `name`, `email` FROM `users` AS `user`;
Executing (default): INSERT INTO `users` (`id`,`name`,`email`) VALUES (NULL,$1,$2);
Executing (default): INSERT INTO `users` (`id`,`name`,`email`) VALUES (NULL,$1,$2);
Executing (default): INSERT INTO `users` (`id`,`name`,`email`) VALUES (NULL,$1,$2);
[result]
{"id":6,"name":"YAMADA","email":"s-yamada@sample.com"}
{"id":7,"name":"HAYASHI","email":"y-hayashi@sample.com"}
{"id":8,"name":"TANAKA","email":"t-tanaka@sample.com"}

結果確認

$ sqlite3 ./sqlite3.db
sqlite> select * from users;
6|YAMADA|s-yamada@sample.com
7|HAYASHI|y-hayashi@sample.com
8|TANAKA|t-tanaka@sample.com
1
4
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
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?