2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

色々な言語で簡単なREPLを実装する #typescript

Last updated at Posted at 2023-12-04

続きです。

REPLとは

こちらの記事を参照してください。

Typescriptで実装する

nodejsのreadlineを利用しています。

$ pnpm init
$ pnpm add -D typescript @types/node
$ vim package.json
// scriptsに追加
  "dev": "node main.js",
  "build": "tsc main.ts",

main.ts

import * as readline from 'readline'

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
})

rl.setPrompt('node> ')
rl.prompt()

rl.on('line', line => {
  try {
    // const prompt = eval(line)
    const prompt = line.trim()
    switch (prompt) {
      case 'exit':
        console.log("Bye!")
        process.exit(0)
      default:
        console.log(prompt)
    }
  } catch (error) {
    console.error("Error: ", error)
  }
  rl.prompt()
}).on('close', () => {
  console.log("\nBye!")
  process.exit(0)
})

実行する

$ pnpm build
$ pnpm dev
node> 1 + 1
1 + 1
node> foobar
foobar
node> baz
baz
node> exit
Bye!

.on('close'...のところでctrl-c、ctrl-dを処理しています。

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?