DEV Community

Cover image for REPL in Nestjs
Rubin
Rubin

Posted on

4

REPL in Nestjs

One of the features of Nestjs is Tte REPL (Read-Eval-Print Loop) mode, a powerful tool that allows you to interactively test and execute code within the context of your NestJS application. This is particularly useful for quick experimentation, testing services, or debugging from the terminal. Here’s a step-by-step guide on how to use the REPL mode in NestJS:

create a new file repl.ts

import { existsSync, mkdirSync } from "node:fs";
import { join } from "node:path";

import { Logger } from "@nestjs/common";
import { repl } from "@nestjs/core";

import { AppModule } from "./app.module";

const logger = new Logger("Repl");

async function bootstrap() {
  const replServer = await repl(AppModule);

  // OPTIONAL: sets up persistant history file for repl, 
  const cacheDirectory = join("node_modules", ".cache");

  if (!existsSync(cacheDirectory))
    mkdirSync(cacheDirectory);

  replServer.setupHistory(
    join(cacheDirectory, ".nestjs_repl_history"),
    (error) => {
      if (error)
        logger.error(error);
    },
  );
}
bootstrap();

Enter fullscreen mode Exit fullscreen mode

Then you can run the app in repl mode with :

npm run start -- --entryFile repl
Enter fullscreen mode Exit fullscreen mode

Even better, add a script on your package.json

"start:repl":"npm run start -- --entryFile repl"
Enter fullscreen mode Exit fullscreen mode

It will initiate an interactive server, from which you can easily access your nest app methods by getting them either as

get(AppService).getAllPosts()
Enter fullscreen mode Exit fullscreen mode

or

$(AppService).getAllPosts()
Enter fullscreen mode Exit fullscreen mode

You can also navigate with the command history with ↕️ arrow keys

Read more at the official documentation

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (1)

Collapse
 
buenandi profile image
Andrés Espinoza

Is it possible to start an interactive REPL when running a dockerized nestjs microservice with docker compose?

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more