2

Is there any way in node.js to fork a new process and run multiple terminal shell commands and execute node.js functions such as fs.writeFileSync from that same process/context.

As an example I want to do the following. Execute all the below in the same process.

exec("git worktree add -b"....);
exec("cd ../");
writeFileSync(...);

This is an express.js applcation, and because multiple users will be accessing the same filesystem at the same time and performing git actions on the same repo, I want to avoid conflicts by spawning a new process for each one.

Alex
  • 317
  • 4
  • 16
  • Have you thought putting all those commands in a single script? – Juan Stiza Jul 29 '16 at 13:04
  • @JuanStiza Not sure how I would run writeFileSync. I guess I would have to put that I a different js file and call it from another shell command? – Alex Jul 29 '16 at 13:15

1 Answers1

-1

Separate it out into a main hub that calls it's children. These children preform any writing/saving that you need to be multithreaded.

Just have the parent call exec("node myWritingChild.js"); when it needs to make one of these writing threads.

Please note: it is usually better to run a child via letting it open through a pipe/forking it. There are many postings about this so look it up if you want to. Also check out these docs.

Loufs
  • 1,596
  • 1
  • 14
  • 22
  • Thanks for that. This seems to partially be working. I put all the commands on a separate js file and used exec command to run them, however it looks like the writeFileSync changes master branch, and not the new branch created by the two other commands. I would expect since the commands 'git worktree add...' and 'cd ../branch' are in teh same process with writeFileSync to do the opposite. – Alex Jul 29 '16 at 15:47
  • @Alex Trying to write to the same file from multiple different sources can cause issues. Make sure each writer has the proper permission and is not getting in the way. Alternatively, have one writing process/child that all the children pipe queue data to if you continue to have issues. – Loufs Jul 29 '16 at 16:09
  • this is working now. The problems was the 'git worktree add -b ' creates a new path and I was accidentally writing to the old one. By putting everything in a new js file and running exec seems to be working as expected. – Alex Aug 01 '16 at 09:51