首页 > 解决方案 > 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?

标签: javascriptnode.jsgitshelljs

解决方案


在您的情况下,您使用的是多行字符串 - 它不太正确。尝试提供一个字符串(一行):

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

推荐阅读