0

我尝试在我的 Java 项目中使用 j2v8 运行 nodeJS 脚本,它运行正常,但我无法获取数组或任何其他 JScript 对象,尽管此功能是通过 j2v8 提供的。此外,该脚本使用一个名为 Blocktrail 的 npm 模块来生成数组。对象的调用在函数 testExportAnalyzer() 中。在这里它抛出对象不包含“测试”。请,谁能解释我如何在我的 Java 代码中使用变量或所需的数组,或者我做错了什么?

public ScriptLoader(String adr) {

    address = adr;
    addressInformation = null;

    NODE_SCRIPT = ""
            +"var test = \"123456\";\n"
            +"var blocktrail = require('/blocktrail-sdk');\n"
            +"var addressInformation = null;\n"
            +"var client = blocktrail.BlocktrailSDK({apiKey : \"xxxxxx\", apiSecret : \"xxxxxx\"});\n"
            +"client.address(\""+address+"\", function(err, address) {\n"
            +" if (err) {\n"
            +" console.log('address ERR', err);\n"
            +" return;\n"
            +"  }\n"
            +" addressInformation = address;"
            +"console.log('address:', address['address'], 'balance:', address['balance'] / blocktrail.COIN, 'sent and received in BTC:', address['sent'] / blocktrail.COIN, address['received'] / blocktrail.COIN, 'number of transactions:', address['total_transactions_out'], address['total_transactions_in']);\n"
            +"});\n"
            +"\n"
            +"client.addressTransactions(\""+address+"\", {limit: 100}, function(err, address_txs) {\n"
            +" console.log('address_transactions', address_txs['data'].length, address_txs['data'][0]);\n"
            +"});";

}

public void executeAnalyzerScript() throws IOException {

    final NodeJS nodeJS = NodeJS.createNodeJS();
      JavaCallback callback = new JavaCallback() {

        public Object invoke(V8Object receiver, V8Array parameters) {
          return "Hello, JavaWorld!";
        }
      };

      nodeJS.getRuntime().registerJavaMethod(callback, "someJavaMethod");
      File nodeScript = createTemporaryScriptFile(NODE_SCRIPT, "addressScript");

      nodeJS.exec(nodeScript);

      while(nodeJS.isRunning()) {
        nodeJS.handleMessage();
      }
      nodeJS.release(); 
}

public void testExportAnalyzer() throws IOException {

    NodeJS nodeJS = null;

    File testScript = createTemporaryScriptFile(NODE_SCRIPT, "Test");

    nodeJS = NodeJS.createNodeJS();
    V8Object exports = nodeJS.require(testScript);

    while(nodeJS.isRunning()) {
        nodeJS.handleMessage();
      }

    System.out.println(exports.contains("test"));
    exports.release();


}

private static File createTemporaryScriptFile(final String script, final String name) throws IOException {
    File tempFile = File.createTempFile(name, ".js.tmp");
    PrintWriter writer = new PrintWriter(tempFile, "UTF-8");
    try {
        writer.print(script);
    } finally {
        writer.close();
    }
    return tempFile;
}

public void setAddress(String input) {
    address = input;
}
4

1 回答 1

-1

通过在 Javascript 代码中编写这样的变量,我取得了一些成功:

global.myvar = "myval";

于 2018-02-11T09:44:46.633 回答