从nodejs运行gradlew

时间:2016-06-23 13:52:24

标签: android node.js gradle child-process spawn

尝试从nodeJS运行gradlew:

const spawn = require('child_process').spawn;
const path = require('path');

function run() {

    var path_dir = path.resolve('./../movies/VanillaApp/android');

    var options = {
        cwd: path_dir
    };

    const ls = spawn('gradlew', ['assembleRelease'], options);

    ls.stdout.on('data', (data) => {
        console.log(`stdout: ${data}`);
    });

    ls.stderr.on('data', (data) => {
        console.log(`stderr: ${data}`);
    });

    ls.on('close', (code) => {
        console.log(`child process exited with code ${code}`);
    });

}



module.exports = {
    run: run
};

终端等价:

> ./gradlew assembleRelease

得到:

events.js:154
throw er; // Unhandled 'error' event
^

Error: spawn gradlew ENOENT
at exports._errnoException (util.js:856:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:178:32)
at onErrorNT (internal/child_process.js:344:16)
at _combinedTickCallback (node.js:377:13)
at process._tickCallback (node.js:401:11)
at Function.Module.runMain (module.js:449:11)
at startup (node.js:141:18)
at node.js:933:3

更新:

我设法使用child_process.exec而不是spawn运行。

2 个答案:

答案 0 :(得分:1)

我自己偶然发现了这个问题,并设法使用--project-dir命令行选项gradlewspawn一起运行:

var taskDone = this.async();

grunt.util.spawn({
    cmd: "my/relative/path/gradlew",
    args: ["clean", "--project-dir", "my/relative/path"],
    opts: {
        stdio: "inherit"
    }
}, function (error, result) {
    if (error) {
        taskDone(false);
    } else {
        taskDone();
    }
});

答案 1 :(得分:0)

我使用的是 react-native,所以我只是在我的根目录中创建了一个脚本文件夹,并添加了一个名为 cleanBuild.js 的文件,内容如下:

#!/bin/node

const { exec } = require("child_process");
const currentOs = require("./getOs");

const os = currentOs();

//===================================================================
function cleanBuild() {
    console.log("\nCleaning project build...");

    exec(`cd android && ${os === 'darwin' ? './gradlew clean' : 'gradlew clean'} && cd ..`, (error, stdout, stderr) => {
        if (error) {
            console.log(`\nFailed to clean build: ${error.message}`);
            return;
        }
        if (stderr) {
            console.log(`\nFailed to clean build: ${stderr}`);
            return;
        }
        console.log(`\nBuild cleaned successfully: \n${stdout}`);
    });
}

//===================================================================
cleanBuild();

现在我可以运行它了:

node ./scripts/cleanBuild.js