Open In App

How to run Java code in Node.js ?

Improve
Improve
Like Article
Like
Save
Share
Report

Node.js is a non-blocking, event-driven JavaScript runtime platform that is built using Chrome’s V8 JavaScript engine. It is mainly used to build scalable projects and applications as it is quite efficient as well as lightweight. It is mainly used for backend purposes while building an application.

Approach: In this particular article, we will be learning how to run Java code using Node.js. Our main approach for achieving this functionality will be to use Bridge API to be able to connect to existing Java APIs.

Follow these steps to run a java program in Node.js:

Install Node.js on your computer, See the steps here.

If it is already installed, skip this step.

Open the folder (or) project where your Java code is stored, and initialize npm.

Syntax:

npm init

Install java as an npm package

Syntax:

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.

Now test the java program by running it in the test.js file.

Example 1: 

Javascript




const java = require('java');
const javaLangSystem = java.import('java.lang.System');
 
javaLangSystem.out.printlnSync('I love gfg!');


Then execute the following command on the terminal of your project:

node test.js

Output:

I love gfg!

Example 2:

Javascript




const java = require('java');
const javaLangSystem = java.import('java.lang.System');
const n = 10
 
javaLangSystem.out.printlnSync(n);


node test.js

Output:

10

Reference: https://www.npmjs.com/package/java.


Last Updated : 03 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads