Run NestJS script from command line
Asked Answered
M

4

5

I want to be able to run a script that parses an XML file using NestJS framework for a proof-of-concept, but I'm not sure how to do it.

I created a scripts directory inside /src and placed my script.ts with an initial console.log there. How can I run commands within that file? Should I change the script.ts file to plain javascript instead of typescript and then run node myscript.ts? What is the correct approach for this manner?

Madly answered 16/3, 2020 at 10:34 Comment(1)
Found a more thorough answer here: #65251157Monocotyledon
M
7

I managed to run my ts file using npx ts-node my-file.ts

Madly answered 17/3, 2020 at 6:44 Comment(0)
L
2

You can add a bin property to your package.json with the name of the command you want to give, and the js file associated with the command. From there, if you were to run "commandName", you should get the command to properly run (after building from Typescript to JavaScript of course). As an example, you can see this. The original command file is written in Typescript, given a shebang of #!/usr/bin/env node to allow for node to be used as the script runner, and then compiled into JavaScript with the rest of the library. From there, I just run ogma <file_name> and let the script take care of the rest.

For you, adding in Nest will be a step on top of this, but still pretty easy to manage as you'll have the entry file use the NestFactory to create the application and then pass the expected data into some sort of handler as described briefly here. Feel free to comment if you have any other questions.

Linson answered 16/3, 2020 at 23:43 Comment(0)
B
1

Try standalone-applications

https://docs.nestjs.com/standalone-applications

or nest-commander

https://docs.nestjs.com/recipes/nest-commander

Buttonhole answered 10/7, 2023 at 21:27 Comment(0)
H
0

What you might be looking for is ts-node. If you have a Typescript class that does the parsing of XML and does not directly depend on something within Nest you can use this. If your application requires you to be running Nest in order to do the parsing of XML you can start the server and make a command line request using CURL following a pattern similar to this

Haldan answered 16/3, 2020 at 16:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.