Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exec in NodeJS using the user's environment?

I am trying to execute a command in Node:

cd "/www/foo/" && "/path/to/git/bin/git.exe" config --list --global

Basically, I want to execute a Git command that returns global configuration (for the current user).

This works fine for me when I execute the command directly on cli. It also works if I do it like this in Node:

var exec = require('child_process').exec;

var config = {
    maxBuffer: 10000 * 1024
};

exec('cd "/www/foo/" && "/path/to/git/bin/git.exe" config --list --global', config, function() {
    console.log(arguments);
});

However, as soon as I specify the environment to the config:

var exec = require('child_process').exec;

var config = {
    maxBuffer: 10000 * 1024,
    env: { // <--- this one
    }
};

exec('cd "/www/foo/" && "/path/to/git/bin/git.exe" config --list --global', config, function() {
    console.log(arguments);
});

Things break:

Command failed: fatal: unable to read config file '(null)/(null)/.gitconfig': No such file or directory

I know the reason, it is because the executed Git program is no longer executed under the user environment (like it is in cli), and can't retrieve the user directory to read global configuration (in Git, global config = user config) and I believe /(null)/(null)/.gitconfig should be /Users/MyName/.gitconfig which does exist.

My question is, how can I specify the current user environment while still being able to specify my own additional environment properties?

like image 399
Tower Avatar asked Nov 05 '11 14:11

Tower


1 Answers

I solved it.

I retrieved the current environment from process.env and extended it with my own properties:

var environment = process.env;
environment.customProp = 'foo';

var config = {
    maxBuffer: 10000 * 1024,
    env: environment
};

So the problem was I missed the entire environment when I overwrote it.

like image 59
Tower Avatar answered Sep 30 '22 19:09

Tower