Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to run Java code in Node.js ?

  • Last Updated : 19 May, 2021

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 a 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.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

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

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



If it is already installed, skip this step.

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

Syntax:

npm init

3.Install java as 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.

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

Example 1: 

Javascript




var java = require('java');
var 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




var java = require('java');
var javaLangSystem = java.import('java.lang.System');
var n=10
  
javaLangSystem.out.printlnSync(n);
node test.js

Output:

10

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!