Skip to content
Related Articles

Related Articles

How to run Java code in Node.js ?

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Expert
  • 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.

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.


npm init

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

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

Example 1: 


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


I love gfg!

Example 2:


var java = require('java');
var javaLangSystem = java.import('java.lang.System');
var n=10

node test.js




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!