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

max picture max · Oct 21, 2013 · Viewed 8.7k times · Source

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?

Answer

lanceball picture lanceball · Jun 16, 2014

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.