'child_process not working in extension(vscode)

I have a program in normal .ts form

var spawn = require('child_process').spawn;
var child = spawn("dir",{shell:true});
child.stdout.on("data",function(data){
console.log('data\n ' + data);});

and the final result is enter image description here

But when i use vscode extension module.

function activate(context) {
console.log('Congratulations, your extension "helloworld-minimal-sample" is now active!');
var spawn = require('child_process').spawnSync;

var child = spawn("dir",{shell:true});

child.stdout.on("data",function(data){
    console.log('data\n ' + data);
});

console.log('stdout here: \n' + child.stdout);

let disposable = vscode.commands.registerCommand('extension.helloWorld', () => {

    vscode.window.showInformationMessage('Hello World!');
});

context.subscriptions.push(disposable);
}

Same api but the shell does not show directory

But this doesn't show the directory. How to solve it?



Solution 1:[1]

Here is how I've got it to work in my project:

/**
  * Creates a child process and calls the AAPI CLI
  * @param command The string CLI command to execute the AAPI
  * @param args The arguments passed to the CLI
*/
export function executeCommand(command: string, args: string): String {
  const cp = require('child_process');

  let argument: string = args;
  let operation: string = command + ' ' + argument;
  let cmd = 'abcd' + operation;

  const proc = cp.spawnSync(cmd, {
    shell: true,
    encoding: 'utf8',
  });

  let procData = proc.stdout.toString();

  if (proc !== null) {
    if (proc.stdout !== null && proc.stdout.toString() !== '') {
      procData = proc.stdout.toString();
    }
    if (proc.stderr !== null && proc.stderr.toString() !== '') {
      const procErr = proc.stderr.toString;
      MessageUtils.showErrorMessage("The '" + operation + "' process failed: " + procErr);
      procData = procErr;
    }
  }

  return procData;
}

Regards, O.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tyler2P