PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 26, 2022

[FIXED] How to execute node command in a node app?

 November 26, 2022     command-line-interface, module, node.js     No comments   

Issue

So basically, I'm trying to make a cli to automate some little task that I'm repeating all the time. And here I want to replace the console.log by something that will run the command instead. I tried with the exec from 'child_process' but it didn't work and i ended with an infinite loader

switch (arg) {
    case "React App":
      console.log(`npx create-react-app ${projectName}`);
      console.log(`cd ${projectName}`);
      console.log(`npm start`);
      break;
    case "Next App":
      console.log(`npx create-next-app@latest ${projectName}`);
      console.log(`cd ${projectName}`);
      console.log(`npm dev`);
      break;

This is the version with the exec

 switch (arg) {
case "React App":
  () => exec(`npx create-react-app ${projectName}`);
  () => exec(`cd ${projectName}`);
  () => exec(`npm start`);
  break;
case "Next App":
  () => exec(`npx create-next-app@latest ${projectName}`);
  () => exec(`cd ${projectName}`);
  () => exec(`npm dev`);
  break;

I searched on many forums and also on stack overflow and I think the fact that I'm not an english native speaker has never been that obvious cause damn I didn't find what i wanted


Solution

run it sequentially with execSync

const execSync = require('child_process').execSync;

//...
switch (arg) {
    case "React App":
        console.log(`npx create-react-app ${projectName}`);
        execSync(`npx create-react-app ${projectName}`);
        console.log(`cd ${projectName}`);
        execSync(`cd ${projectName}`);
        console.log(`npm start`);
        execSync(`npm start`);
        break;
    case "Next App":
        console.log(`npx create-next-app@latest ${projectName}`);
        execSync(`npx create-next-app@latest ${projectName}`);
        console.log(`cd ${projectName}`);
        execSync(`cd ${projectName}`);
        console.log(`npm dev`);
        execSync(`npm dev`);
        break;
}


Answered By - traynor
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing