node-java-maven - manages your node-java classpath by using maven dependency management.
Installation
$ npm install java
Notes:
node-gyp requires python 2.x not python 3.x. See nodejs/node-gyp#155 for more details.
If you see an error such as "Call to 'node findJavaHome.js' returned exit status 1"
Try running node findJavaHome.js in the node-java directory to see the full failure message.
If you are having problems finding 'jni.h'. Make sure you have the JDK installed not just the JRE. If you are using
OpenJDK you want the openjdk-7-jdk package, not openjdk-7-jre. Mavericks users see Issue #86 if you run into this.
Installation Ubuntu
sudo apt install make g++
If u've error (on global installation): EACCES user nobody does not have permission to access the dev dir /root/.cache/node-gyp/10.16.0, then just run: npm i -g java --unsafe-perm
Installation OSX
If you run into strange runtime issues, it could be because the Oracle JDK does not advertise itself as available for JNI. See Issue 90 for more details and manual workarounds. If this does occur for you, please update the issue.
when using the windows SDK 7.1 command prompt (64 bits) be sure to setenv.cmd /Release /x86
If you get ENOENT errors looking for <nodepath>\node_modules\node-gyp\.., ensure you have node-gyp installed as a global nodule:
npm install -g node-gyp
If you get D9025 warnings and C1083 errors when looking for .sln or .h files, be sure you've got the node-gyp's dependencies, as explained here.
Alternatively, Windows users can easily install all required tools by running the following command in PowerShell as administrator. For more information see windows-build-tools project page:
Some issues with the OpenSDK7 so take the Oracle version for compiling.
Docker
If you want to play with node-java but don't want to setup the build environment you can run it in docker.
docker run -it joeferner/node-java bash
Then inside the docker container create a directory and run
npm install --unsafe-perm java
Then create a file called test.js with the following contents
var java = require('java');
var javaLangSystem = java.import('java.lang.System');
javaLangSystem.out.printlnSync('Hello World');
Then run
node test.js
Java 1.8 support
Manual compilation for Java 1.8 support requires additional steps:
./compile-java-code.sh
./compile-java8-code.sh
node-gyp configure build
npm test
Java 1.8 language features can be used in Java classes only if a Java 1.8 JRE is available. The script compile-java8-code.sh is used only to compile java classes used in the 'test8' unit tests, but these classes are checked into the test8/ directory. Note that unit tests in the test8/ directory will pass (by design) if run against a Java 1.7 JRE, provided that a java.lang.UnsupportedClassVersionError is caught with the message 'Unsupported major.minor version 52.0' (the expected behavior when Java 1.8 language features are used in an older JRE).
JavaScript only supports 32-bit integers. Because of this java longs must be treated specially.
When getting a long result the value may be truncated. If you need the original value there is
a property off of the result called "longValue" which contains the un-truncated value as a string.
If you are calling a method that takes a long you must create it using java.newInstance.
varjavaLong=java.newInstanceSync("java.lang.Long",5);console.log('Possibly truncated long value: '+javaLong);console.log('Original long value (as a string): '+javaLong.longValue);java.callStaticMethodSync("Test","staticMethodThatTakesALong",javaLong);
Exceptions
Exceptions from calling methods either caught using JavaScript try/catch block or passed
to a callback as the first parameter may have a property named "cause" which has a reference
to the Java Exception object which caused the error.
AsyncOptions: control over the generation of sync, async & promise method variants.
As of release 0.4.5 it became possible to create async methods that return promises by setting the asyncOptions property of the java object. With release 0.4.7 this feature is extended to allow changing the suffix assigned for sync and async method variants, and to further configure this module to optionally omit generation of any of these variants.
Example:
varjava=require("java");java.asyncOptions={asyncSuffix: undefined,// Don't generate node-style methods taking callbackssyncSuffix: "",// Sync methods use the base name(!!)promiseSuffix: "Promise",// Generate methods returning promises, using the suffix Promise.promisify: require('util').promisify// Needs Node.js version 8 or greater, see comment below};java.classpath.push("commons-lang3-3.1.jar");java.classpath.push("commons-io.jar");java.import("java.util.ArrayList");// see NOTE belowjava.newInstancePromise("java.util.ArrayList").then(function(list){returnlist.addPromise("item1");}).then(function(list){returnlist.addPromise("item2");}).catch(function(err){/* handle error */});
NOTES:
If you want the defacto standard behavior, simply don't set java.asyncOptions.
If you do provide asyncOptions, be aware that this module will not generate method variants of a given flavor if you don't provide a string value for the corresponding suffix (asyncSuffix, syncSuffix, promiseSuffix). In the example above, the application is configured to omit the method variants using node-style async callback functions.
If you provide asyncOptions.promiseSuffix then you must also set asyncOptions.promisify to a function that promisifies a node-style async function. I.e. the provided function must take as input a function whose last argument is a node callback function, and it must return an equivalent promise-returning function. Several Promises/A+ libraries provide such functions, but it may be necessary to provide a wrapper function. See testHelpers.js for an example.
For promisify implementation, if you are using Node.js version 8.0.0 or newer then promisify: require('util').promisify will work out of the box. If you need to support and older Node.js version then an implementation needs to be provided, for example, promisify: require("when/node").lift
If you provide asyncOptions.promisify then you must provide a non-empty string for asyncOptions.promiseSuffix.
Either (but not both) asyncSuffix or syncSuffix can be the empty string. If you want the defacto standard behavior for no suffix on async methods, you must provide an empty string for asyncSuffix.
We've tested promises with five Promises/A+ implementations. See testHelpers.js for more information.
NOTE: Due to specifics of initialization order, the methods java.newInstancePromise, java.callMethodPromise, and java.callStaticMethodPromise are not available until the JVM has been created. You may need to call some other java method such as java.import() to finalize java initialization, or even better, the function java.ensureJvm().
Special note about the exported module functions newInstance, callMethod, and callStaticMethod.
These methods come in both async and sync variants. If you provide the promisify and promiseSuffix attributes in asyncOptions then you'll also get the Promises/A+ variant for these three functions. However, if you change the defacto conventions for the syncSuffix (i.e. 'Sync') and/or asyncSuffix (i.e. '') it will not affect the naming for these three functions. I.e. no matter what you specify in asyncOptions, the async variants are named newInstance, callMethod, and callStaticMethod, and the sync variants are named newInstanceSync, callMethodSync, and callStaticMethodSync.
Varargs support
With v0.5.0 node-java now supports methods with variadic arguments (varargs). Prior to v0.5.0, a JavaScript call to a Java varargs method had to construct an array of the variadic arguments using java.newArray(). With v0.5.0 JavaScript applications can simply use the variadic style.
In most cases it is still acceptable to use java.newArray(). But it is now possible to pass a plain JavaScript array, or use the variadic style. For example, consider these snippets from the unit test file test/varargs-test.js:
Note that when passing a JavaScript array (e.g. ['a', 'b', 'c']) for a varargs parameter, node-java must infer the Java type of the array. If all of the elements are of the same JavaScript primitive type (string in this example) then node-java will create a Java array of the corresponding type (e.g. java.lang.String). The Java types that node-java can infer are: java.lang.String, java.lang.Boolean, java.lang.Integer, java.lang.Long, and java.lang.Double. If an array has a mix of Integer, Long, and Double, then the inferred type will be java.lang.Number. Any other mix will result in an inferred type of java.lang.Object.
With v0.5.1 a new API is available to make it easier for a complex application to have full control over JVM creation. In particular, it is now easier to compose an application from several modules, each of which must add to the Java classpath and possibly do other operations just before or just after the JVM has been created. See the methods ensureJvm and registerClient. See also several of the tests in the testAsyncOptions directory.
Release Notes
v0.5.0
Support for varargs. This change is not 100% backwards compatible, but the fix is generally easy and results in more natural code.
v0.2.0
java.lang.Long and long primitives are handled better. See
(Issue #37) and
(Issue #40).
java.asyncOptions={asyncSuffix: undefined,// Don't generate node-style methods taking callbackssyncSuffix: "",// Sync methods use the base name(!!)promiseSuffix: "Promise",// Generate methods returning promises, using the suffix Promise.promisify: require('util').promisify// Needs Node.js version 8 or greater, see comment belowifReadOnlySuffix: "_alt"};
请发表评论