Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use CommonJS modules with Oracle's new Nashorn JS Engine?

I'm looking for a module system for Nashorn. From what I can tell, CommonJS is the way to go concerning modules for JS. I have looked through the list (here and here) and have found little in the way of a CommonJS implementation for Java.

Narwhal is no longer active and it's documentation is no longer hosted on GitHub. Is there an existing CommonJS implementation which supports Java or should I start a new project?

like image 247
max Avatar asked Oct 21 '13 16:10

max


People also ask

What is replacement for Nashorn?

GraalVM can step in as a replacement for JavaScript code previously executed on the Nashorn engine. GraalVM provides all the features for JavaScript previously provided by Nashorn. Many are available by default, some are behind flags, and others require minor modifications to your source code.

Will CommonJS be deprecated?

CommonJS will likely be supported in nodejs for a long time as there are still millions of lines of code written using it. It is the original module loading mechanism in nodejs. It is not deprecated.

Which JavaScript engine is replaced with Nashorn?

Technical Article. Until Java SE 7, JDKs shipped with a JavaScript scripting engine based on Mozilla Rhino. Java SE 8 will instead ship with a new engine called Oracle Nashorn, which is based on JSR 292 and invokedynamic .

What is CommonJS module in JavaScript?

CommonJS is a set of standards used to implement modules on JavaScript. The project was started by Mozilla engineer Kevin Dangoor in 2009. CommonJS is mainly used in server-side JS apps with Node, as browsers don't support the use of CommonJS.


1 Answers

Have a look at jvm-npm here https://github.com/nodyn/jvm-npm. This project is used by nodyn as the CommonJS module system. It is NPM-aware, meaning you can load modules directly from NPM, but it does not provide any of the Node.js API.

Here is a simple example usage:

$ npm install pegjs
npm http GET https://registry.npmjs.org/pegjs
npm http 200 https://registry.npmjs.org/pegjs
[email protected] node_modules/pegjs
$ jrunscript
nashorn> typeof require
undefined
nashorn> load('./jvm-npm.js')
nashorn> typeof require
function
nashorn> var PEG = require('pegjs');
nashorn> typeof PEG
object

It is primarily all Javascript, but the actual loading of files from the filesystem and such is done using Java.

like image 94
lanceball Avatar answered Sep 19 '22 14:09

lanceball