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.

2
  • Have you thought putting all those commands in a single script? Commented Jul 29, 2016 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? Commented Jul 29, 2016 at 13:15

1 Answer 1

-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.

Sign up to request clarification or add additional context in comments.

3 Comments

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 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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.