How to Run Java Code in Node.js ?
Running Java code within a Node.js environment can be useful for integrating Java-based libraries or leveraging Java’s robust capabilities within a JavaScript application. This article will guide you through the steps required to execute Java code from a Node.js application, covering various methods and tools available to facilitate this integration.
Why Run Java Code in Node.js?
Integrating Java code with Node.js can offer several advantages:
- Access to Java Libraries: Leverage the rich ecosystem of Java libraries for tasks such as data processing, machine learning, or web services.
- Performance: Utilize Java’s high performance for CPU-intensive tasks.
- Legacy Code Integration: Integrate with existing Java applications or legacy codebases.
Steps to Run JAVA Program in NodeJS
Install Node.js on your computer, See the steps here. If it is already installed, skip this step.
Step 1:
Open the folder (or) project where your Java code is stored, and initialize npm.
npm init
Step 2:
Install java as an npm package
npm install java
Note: Python and JDK need to be installed on your system for this to run error-free as the package to be installed uses gyp else you’ll end with a similar set of errors :
Learn how to download Python from here and JDK from here and set up the environment variable to both along with their respective paths.
Alternatively, you can add the java package directly to the package.json file in your project in the dependencies column.
Note: This should be the last resort i.e only if any other method doesn’t work.
Example 1: Implementation to test the java program by running it in the test.js file.
const java = require('java');
const javaLangSystem = java.import('java.lang.System');
javaLangSystem.out.printlnSync('I love gfg!');
Step to Run Application: Run the application using the following command from the root directory of the project
node test.js
Output:
I love gfg!
Example 2: Implementation to test the java program by running it in the test.js file with another example.
const java = require('java');
const javaLangSystem = java.import('java.lang.System');
const n = 10
javaLangSystem.out.printlnSync(n);
Step to Run Application: Run the application using the following command from the root directory of the project
node test.js
Output:
10
Reference: https://www.npmjs.com/package/java.