Home > other >  exec function in Angular
exec function in Angular

Time:01-23

I am trying to run a bash command through Angular.
After some research i found the code below that should be working

import { ChildProcess, exec } from 'child_process';

@Injectable({
  providedIn: 'root'
})
export class CommandService {
  runCommand(command: string): Promise<string> {
    return new Promise((resolve, reject) => {
      exec(command, (error: Error, stdout: string, stderr: string) => {
        if (error) {
          reject(error);
        }
        resolve(stdout);
      });
    });
  }
}

then i call it in my .ts file


import { CommandService } from './command.service';

export class YourComponent {
  output: string;

  constructor(private commandService: CommandService) {}

  run() {
    this.commandService.runCommand('ls -la')
    .then(output => this.output = output)
    .catch(error => console.log(error));
  }

The problem is that even though there doesnt seem to have any errors, when i try to run it it says:

error TS2307: Cannot find module 'child_process' or its corresponding type declarations.

3 import { ChildProcess } from "child_process";

, even though i can see that the file exists in my project.
Is there something i can do to fix that ? If not can i run a command some other way through Angular ?
Thanks in advance

CodePudding user response:

I afraid you can't do that dave Jason.

child_process is available in a nodeJS runtime and Angular runs in a browser. That's 2 different runtimes which only have in common to use JS as a language.

Also, don't expect to be able to run a bash command from the browser that would be a MASSIVE security issue.

CodePudding user response:

Matthieu Riegler is right, you cannot access OS features from within the browser environment. That being said, depending on what you want to do, you could have the bash command run at build time (e.g. with an npm script) or if you really need it at run time and happen to have a backend as well, you could expose an endpoint that runs the bash command on demand and return the result over http.

  • Related