目前好像没有更好的方案去实现在node环境下执行js,这种方案需要配合js代码,目标js只能为这个groovy服务
groovy代码
// Groovy script to execute Node.js script
static def runJsScript(String scriptPath, String argument) {
    // Create a command 
    def command = ["node", scriptPath, argument]
    // Create a ProcessBuilder with the command
    def processBuilder = new ProcessBuilder(command)
    // Start the process
    def process = processBuilder.start()
    // Capture the output of the process
    def output = new StringWriter()
    def error = new StringWriter()
    process.consumeProcessOutput(output, error)
    // Wait for the process to complete
    process.waitFor()
    // Return the output and error streams
    return [output.toString().trim(), error.toString().trim()]
}
// Path to the JavaScript file
def scriptPath = "./a.js"
// Argument to pass to the JavaScript function
def argument = "World"
// Call the JavaScript function
def (output, error) = runJsScript(scriptPath, argument)
if (error) {
    println "Error: $error"
} else {
    println "Output: $output"
}
js代码
function greet(name) {
    return `Hello, ${name}!`;
}
console.log(greet(process.argv[2]));需要传参多少个参数,需要在js块拼接 process.argv[2] process.argv[3]
执行多个参数
groovy
static def runJsScript(String scriptPath, String... arguments) {
    def command = ["node", scriptPath]
    arguments.each {command.add(it)}
    def processBuilder = new ProcessBuilder(command)
    def process = processBuilder.start()
    def output = new StringWriter()
    def error = new StringWriter()
    process.consumeProcessOutput(output, error)
    process.waitFor()
    return [output.toString().trim(), error.toString().trim()]
}js
function greet(name,value) {
    return `Hello, ${name}: ${value}`;
}
console.log(greet(process.argv[2],process.argv[3]));其实还是有个小坑 传参json会被解析成js对象,就导致js拿到的数据已经是处理过的了,后面的流程是会受影响的。 
解决方案:可以在添加额外参数时进行检验,判断当前字符串是否可以被转换为json对象,如果可以就做转义处理,str.replace('"','\"') 
可以封装成一个工具类使用
class Execute {
    static def js(String scriptPath, String... arguments) {
        
        def command = ["node", scriptPath]
        // 如果是json格式,就进行转义,防止传参过程中被解析
        arguments.each {
            if (isValidJson(it)) {
                command.add(it.replace('"','\\""'))
            }else command.add(it)
        }
        def processBuilder = new ProcessBuilder(command)
        def process = processBuilder.start()
        def output = new StringWriter()
        def error = new StringWriter()
        process.consumeProcessOutput(output, error)
        process.waitFor()
        if (error!=null && (error as String) != ""){
            throw new Exception("js脚本出错:+$error")
        }
        return output.toString().trim()
    }
    // 判断字符串是不是json格式
    static private boolean isValidJson(String str) {
        def s = new JsonSlurper()
        try {
            s.parseText(str)
            return true
        } catch (Exception e) {
            return false
        }
    }
} 
        
       
     
           
          
评论 (0)