Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodeJS exec does not work for "cd " shell cmd

var sys = require('sys'),     exec = require('child_process').exec;  exec("cd /home/ubuntu/distro", function(err, stdout, stderr) {         console.log("cd: " + err + " : "  + stdout);         exec("pwd", function(err, stdout, stderr) {             console.log("pwd: " + err + " : " + stdout);             exec("git status", function(err, stdout, stderr) {                 console.log("git status returned " ); console.log(err);             })         })     }) 

cd: null :  pwd: null : /  git status returned  { [Error: Command failed: fatal: Not a git repository (or any of the parent directories): .git ] killed: false, code: 128, signal: null } 

nodeJS exec does not work for "cd " shell cmd. as you see below, pwd works, git status is trying to work but fails because it is not executed in a git directory, but cd cmd fails stopping further successful execution of other cmds. Tried in nodeJS shell as well as nodeJS+ExpressJS webserver.

like image 274
user1447121 Avatar asked Mar 26 '13 05:03

user1447121


People also ask

How do I run an exec in node JS?

The exec() function in Node. js creates a new shell process and executes a command in that shell. The output of the command is kept in a buffer in memory, which you can accept via a callback function passed into exec() .

How do I run a node JS command line?

The usual way to run a Node. js program is to run the globally available node command (once you install Node. js) and pass the name of the file you want to execute. While running the command, make sure you are in the same directory which contains the app.

How do I open a node JS terminal in Windows?

Node.js files must be initiated in the "Command Line Interface" program of your computer. How to open the command line interface on your computer depends on the operating system. For Windows users, press the start button and look for "Command Prompt", or simply write "cmd" in the search field.


1 Answers

Each command is executed in a separate shell, so the first cd only affects that shell process which then terminates. If you want to run git in a particular directory, just have Node set the path for you:

exec('git status', {cwd: '/home/ubuntu/distro'}, /* ... */); 

cwd (current working directory) is one of many options available for exec.

like image 141
icktoofay Avatar answered Sep 30 '22 17:09

icktoofay