Search code examples
javascriptnode.jsgitshelljs

Using NPM ShellJS to execute a Git command in Node returns an empty string inside `stdout`


I'm using NPM ShellJS to execute the following Git command inside a Node script:

git for-each-ref --sort=v:refname --format "tag: %(refname:strip=2) message: %(subject) date: %(authordate:iso)" refs/tags

If I run this command inside a normal command line window, it works perfectly and results in an output similar to this:

tag: v2.20.0-rc0 message: Git 2.20-rc0 date: 2018-11-18 18:25:38 +0900
tag: v2.20.0-rc1 message: Git 2.20-rc1 date: 2018-11-21 23:25:15 +0900
tag: v2.20.0-rc2 message: Git 2.20-rc2 date: 2018-12-01 21:45:08 +0900

However, when I run this command in Node using ShellJS, the contents of stdout is an empty string:

const shell = require('shelljs');

let tagInfo = shell.exec(`
  git for-each-ref --sort=v:refname --format "tag: %(refname:strip=2) message: %(subject) date: %(authordate:iso)" refs/tags
`);

console.log('tagInfo', tagInfo.stdout); // empty string

How do I get the output as specified about, instead of the empty string?


Solution

  • In your case you are using a multi-line string - it is not quite correct. Try to provide one string (in one line):

    let tagInfo = shell.exec(`git for-each-ref --sort=v:refname --format "tag: %(refname:strip=2) message: %(subject) date: %(authordate:iso)" refs/tags`);