问题
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?
回答1:
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.
回答2:
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
回答3:
I managed to run my ts file using npx ts-node my-file.ts
来源:https://stackoverflow.com/questions/60704316/run-nestjs-script-from-command-line