Skip to content

Latest commit

 

History

History
225 lines (159 loc) · 10.1 KB

README-en.md

File metadata and controls

225 lines (159 loc) · 10.1 KB

Language:   中文   |   English

nodejs-jre

npm GitHub Static Badge Static Badge

Nodejs-jre will download the Java Runtime Environment (JRE) or Java Development Kit (JDK) from the open source mirror website. And embed it into your node.js application and provide usage way.

Current supported JRE and JDK versions:8, 11, 17, 18, 19, 20, 21.

Installation

npm install --save nodejs-jre

Basic Usage

Installing nodejs-jre will automatically download jre8. If this is not the resource type or version you want, you can call the install API to download the corresponding resource. (Downloads of the same resource type will be overwritten, and different types can coexist. For example, you cannot have both jre8 and jre11, but you can have both jre8 and jdk11)

const { install } = require('nodejs-jre');

// Install jre17
install('jre', 17);

// Install jdk11 and output after installation: jdk11 is successfully installed
install('jdk', 11).then(() => {
    console.log('jdk11 is successfully installed');
});

It should be noted that except for install, all other APIs of nodejs-jre require corresponding resources to be used. For example, to use jre.java, ensure that JRE is installed, and to use jdk.javac, ensure that JDK is installed.

Next, we will learn the basic usage of nodejs-jre through Java's "Hello World" program. Firstly, we prepare a raw Java file called test/Hello.java in the test folder under the root directory.

public class Hello {
    public static void main(String[] args) {
        System.out.print("Hello " + args[0] + "!");
    }
}

Compile test/Hello.java into a class file and run it by running the following code.

const { jre, jdk } = require('nodejs-jre');

// Compile synchronously
jdk.javacSync('test/Hello.java');

// Run asynchronously and output results
let outcome = '';
const child = jre.java('Hello', ['-cp', 'test'], ['world']);

child.stdout.on('data', data => {
    outcome = data;
});
child.stderr.on('data', data => {
    console.log('Error: ' + data);
})
child.on('close', code => {
    console.log(outcome);   // Hello world!
})

API

The APIs of nodejs-jre are basically based on wrapper of child_process.spawn and child_process.spawnSync. Except for install, all APIs have synchronous and asynchronous two types, which share the same parameters. The synchronization API will not be elaborated too much, and specific usage can refer to child_process.spawnSync.

install(driver, version)

Download the specified version of JRE or JDK asynchronously and integrate it into the project, and this method will return a Promise which becomes fulfilled when the integration is complete. When npm i nodejs-jre, it will automatically call install ('jre', 8) to download and install jre8.

Params:

  • driver {String} — Type of resource
    • Required, only support 'jre' and 'jdk'
  • version {String | Number} — Version of resource
    • Required, currently only support 8, 11, 17, 18, 19, 20, 21

jre.java(source[, args][, execArgs][, options])

Load the specified class or file, and launch the Java program. Specific usage can refer to official document.

Params:

  • source {String} — The class name or jar file to start, it needs to be used with different args
    • Required, e.g. 'Hello', 'xxx.jar'
  • args {String[]} — Command line options used by java
    • Optional, default: []
    • e.g. ['-cp', 'test'], ['-jar', 'xxx.jar'], ...
    • View all available options list here
  • execArgs {String[]} — Parameters passed to the main class
    • Optional, default: []
    • e.g. ['world'], ...
  • options {Object} — Options pass to child_process.spawn used in the options section
    • Optional, default: { encoding: 'utf-8' }
    • View all available options list here

This function returns a ChildProcess instance, to handle the execution results and error information of the process. For details, please refer to child_process.spawn.

const { jre } = require('nodejs-jre');

/*** Some Examples ***/

// Merge the environment variables of the parent and child processes, and run the Hello.class file
jre.java('Hello', [], [], { env: ...process.env });  

// Run Test.jar file
jre.java('Test.jar', ['-jar']);

// Run the class org.xxx.yyy.ZZZ in the a.jar file in Windows 
// And pass two Params, '12' and '34', to it at the same time
jre.java('org.xxx.yyy.ZZZ', ['-cp', ';.jar/a.jar'], ['12', '34']);  

jdk.javac(sourceFile[, args][, options])

Read Java class and interface definitions and compile them into bytecode and class files. Specific usage can refer to official document.

Params:

  • sourceFile {String | String[]} — One or more source files to be compiled, passed in as an array, when there are multiple files
    • Required, e.g. 'Hello.java', ['Hello.java', 'World.java']
  • args {String[]} — Command line options used by javac
    • Optional, default: []
    • e.g. ['-d', 'test']
    • View all available options list here
  • options {Object} — Options pass to child_process.spawn used in the options section
    • Optional, default: { encoding: 'utf-8' }
    • View all available options list here

This function returns a ChildProcess instance, to handle the execution results and error information of the process. For details, please refer to child_process.spawn.

const { jdk } = require('nodejs-jre');

/*** Some Examples ***/

// Merge the environment variables of the parent and child processes, and compile the Hello.java file in the test folder
jdk.javac('test/Hello.java', [], { env: ...process.env });  

// Compile the Hello.java file in the test folder and the World.java file in the current directory
// And generate the compiled file in the class folder
jdk.javac(['test/Hello.java', 'World.java'], ['-d', 'class']);

jdk.jar(mode, jarPath[, args][, options])

Create an archive for classes and resources, and to manipulate or restore individual classes or resources from an archive. Specific usage can refer to official document.

Params:

  • mode {String} — Main operation modes of jar command
    • Required, e.g. 'tf', -cf, ...
  • jarPath {String} — Path to the jar file to operate on
    • Required, e.g. 'jars/xxx.jar'
  • args {String | String[]} — Command line parameters used by jar
    • Optional, default: []
    • e.g. 'class/xxx.class', ['--manifest', 'mymanifest', '-C', 'foo/'], ...
    • View all available parameters list here
  • options {Object} — Options pass to child_process.spawn used in the options section
    • Optional, default: { encoding: 'utf-8' }
    • View all available options list here

This function returns a ChildProcess instance, to handle the execution results and error information of the process. For details, please refer to child_process.spawn.

const { jdk } = require('nodejs-jre');

/*** Some Examples ***/

// List the file directory of test.jar in the current directory
jdk.jar('-tf', './test.jar');

// Pack the class files a and b under the class folder into jar packages and place them in the jar directory and name them test.jar
jdk.jar('cf', 'jars/test.jar', ['class/a.class', 'class/b.class']);

Extension

If the command you need is not in the existing APIs, you can access the bin directory of the installed JRE or JDK through jre.bin and jdk.bin for expansion.

Chat

The author Duskstar, a leisurely and happy-go-lucky front-end engineer. Occasionally build some open source projects and occasionally write blogs.

If you have any doubts about this project, or desire to have technical exchange, let's make friends🍻:

Because of fate, we met here by chance. Feel free to leave a Star ⭐ to this repo, greatly appreciate.

License

MIT Copyright (c) 2023 Duskstar