W
W
Wasya UK2020-09-15 19:16:19
Node.js
Wasya UK, 2020-09-15 19:16:19

How to run a script in node.js?

I have the serve module installed in my node . How can I launch it to a specific directory?
I tried to run it just like that, but it didn’t work out (But you can’t install the module globally ...

const { exec } = require('child_process');

module.exports = class Server {
  projectPath = null;

  constructor(projectPath) {
    if (typeof projectPath !== "string") {
      throw new Error("Project path must be a string!");
    }

    this.projectPath = projectPath;
  }

  start() {
    exec(`serve ${this.projectPath}`, (error, stdout, stderr) => {
      if (error) {
        console.error(`exec error: ${error}`);
        return;
      }
      console.log(`stdout: ${stdout}`);
      console.error(`stderr: ${stderr}`);
    });
  }
}

'serve' is not recognized as an internal or external command,
operable program or batch file.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kocherman, 2020-09-15
@dmc1989

Just write the full path to the file, escaping spaces with a backslash \ .
Something like:

exec(`/home/user/projects/node_modules/serve/bin/serve ${this.projectPath}`

exec(`C:\\Documents\\projects\\node_modules\\serve\\bin\\serve ${this.projectPath}`

Just find the executable before that.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question