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?

More than 3 years have passed since last update.

TypeORMの初期サンプル実行やCLIツール作ろうとするときプロセスが終わらない問題の解決

0
Last updated at Posted at 2021-08-22

TypeORMでプロジェクトを下記コマンドで作成する

typeorm init --name MyProject --database mysql

src/index.ts にサンプルファイルが出力される

import "reflect-metadata";
import {createConnection} from "typeorm";
import {User} from "./entity/User";

createConnection().then(async connection => {

    console.log("Inserting a new user into the database...");
    const user = new User();
    user.firstName = "Timber";
    user.lastName = "Saw";
    user.age = 25;
    await connection.manager.save(user);
    console.log("Saved a new user with id: " + user.id);

    console.log("Loading users from the database...");
    const users = await connection.manager.find(User);
    console.log("Loaded users: ", users);

    console.log("Here you can setup and run express/koa/any other framework.");

}).catch(error => console.log(error));

これを下記で実行するとコンソールが処理が終了せずに固まる

ts-node src/index.ts
Inserting a new user into the database...
Saved a new user with id: 3
Loading users from the database...
Loaded users:  [
  User { id: 1, firstName: 'Timber', lastName: 'Saw', age: 25 }
]
Here you can setup and run express/koa/any other framework.
 <ここでフリーズする=処理が抜けない>

mysql> show processlist;で確認すると<ここでフリーズする>の箇所ではコネクションは活きている状態になっている。

typeormを使ってCLIツールなど使うときこれだと困るので、一つの解決策は process.exit()を差し込めばいいがさすがにそれは最終手段なのでコネクションをクローズすることで処理が抜けるようになった。

import "reflect-metadata";
import {createConnection} from "typeorm";
import {User} from "./entity/User";

createConnection().then(async connection => {

    const users = await connection.manager.find(User)
    console.log("Loaded users: ", users)
    await connection.close() // ここを追加

}).catch(error => console.log(error));

TypeORMのサンプルは明示的にcloseの記載はないので、明示的に終了したいときはcloseをいれるのが良さそう。

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?