Search code examples
javascriptnode.jsvisual-studio-codenpmvscode-extensions

How to call NodeJS script inside custom VSCode Extension?


In one of my projects I created a NodeJS script. Now I would like to create a VSCode extension.

How can I link this script to a command inside my custom made extension?

The script should be included in the extension package.

I tried running the script from the terminal, but it wouldn't load the script from within my package.

const terminal = vscode.window.createTerminal( 'My Node Script' );
terminal.show();
terminal.sendText( 'npm run myscript', true );

How can I achieve this?

-- Update 02/01/2024

Colored code

The colored output seems to work as long as I set Git bash as my default terminal in Windows, but I wouldn't like to show the actual echo command displayed in the terminal.

Basically the script that I am running is something like:

 - Blue color log line: Starting script..
 - Terminal command: abc
 - Blue color log line: Completed step 1
 - Terminal command: xyz
 - Blue color log line: Completed step 2
 - .. etc etc
 - Green color log line: Completed

With terminal commands and echo's perferably hidden from output because it looks like this:

enter image description here

While it is waiting for a command ran by the script, it actually shows like the script completed altogether, but then proceeds to send out more commands (sendText()) when the script arrives in the next part.

So the script is not executed in a single terminal execution

What I hope to achieve:

enter image description here

The closest I got was using sendTerminal( 'stty -echo' ) from https://askubuntu.com/a/1384471. It would not show the input text anymore, but still show newlines and return to the terminal after each command.


Solution

  • Finally I found a solution

    By including the Node script into the extension as a command, then by creating a new terminal, running commands using child_process and sending colored output text to the terminal.

    To make the terminal logs appear similar to running the Node script, and in color, see below.

    Code

    Using stty -echo not to display command input characters
    https://askubuntu.com/a/1384471

    Using export PS1='' not to display prompt header
    https://askubuntu.com/a/16729/1569633

    Using echo -n (and -e for colors) when echoing text to avoid appending new lines