- Запускаем Node.js на JVM
- J2V8
- Совместное использование Node.js и JVM
- NPM
- Подключение J2V8
- От переводчика
- Saved searches
- Use saved searches to filter your results more quickly
- cesarvr/Ella
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- Readme.md
- About
Запускаем Node.js на JVM
Прошли те дни, когда целые компании зависели от одного поставщика технологий. Даже маленькие фирмы и любители найдут оптимальное для себя решение, объединяя технологии в одном проекте. Долгое время Java держала первенство среди серверных технологий. Но сегодня Node.js повсюду.
Но даже с ростом популярности Node.js и JavaScript, Java не теряет силу. Кроме того, немногие организации могут позволить себе перенести всю платформу с JVM на Node.js. Это значит, что компания должна либо продолжать использовать текущий стек технологий, либо запускать несколько стеков, которые будут общаться через сетевое API. Однако есть и другой способ: запустить Node.js прямо в процессе JVM. И J2V8, наконец, сделала это возможным.
J2V8
J2V8 это набор коннекторов к V8 для Java. J2V8 упаковывает V8 как динамическую библиотеку и предоставляет Java API для V8 через Java Native Interface (JNI). С J2V8 Вы можете выполнять JavaScript используя V8 также, как если бы использовали Rhino или Nashorn.
Изначально J2V8 был разработан для предоставления высокопроизводительного JavaScript в Tabris.js, кросс-платформенной мобильной библиотеке.
За последние месяцы я настраивал сборку Node.js как динамической библиотеки и обеспечивал взаимодействие с Java API для неё. Теперь вы можете выполнять скрипты для Node.js прямо из Java. В отличии от прочих решений, которые пытаются реализовать Node.js используя другие движки, это настоящий Node.js со всеми багами и возможностями. Node.js запускается в том же процессе что и JVM и всё взаимодействие происходит синхронно через JNI.
Совместное использование Node.js и JVM
J2V8 предоставляет API для выполнения скриптов в Node.js, вызова функций JavaScript из Java и наоборот, подключения NPM модулей и запуска очереди сообщений Node.js. Все модули ядра Node.js также присутствуют.
Запуск Node.js на JVM позволяет легче провести миграцию для любого, кто использует большой Java стек, но хочет начать использовать Node.js. Например, Вы можете запустить на Node.js сервер (такой как Express.js) и вызывать существующие методы Java для обработки запросов.
static String NODE_SCRIPT = "var http = require('http');\n" + "" + "var server = http.createServer(function (request, response) );\n" + " response.end(someJavaMethod());\n" + ">);\n" + "" + "server.listen(8000);\n" + "console.log('Server running at http://127.0.0.1:8000/');"; public static void main(String[] args) throws IOException < final NodeJS nodeJS = NodeJS.createNodeJS(); JavaCallback callback = new JavaCallback() < public Object invoke(V8Object receiver, V8Array parameters) < return "Hello, JavaWorld!"; >>; nodeJS.getRuntime().registerJavaMethod(callback, "someJavaMethod"); File nodeScript = createTemporaryScriptFile(NODE_SCRIPT, "example"); nodeJS.exec(nodeScript); while(nodeJS.isRunning()) < nodeJS.handleMessage(); >nodeJS.release(); >
NPM
Вдобавок к вызову существующих методов Java из Node.js, J2V8 предоставляет возможность вызывать JavaScript функции (в том числе NPM модулей) прямо из Java. С такой интеграцией, Java пользователи могут сразу начать использовать NPM модули прямо в JVM. Например, Вы можете использовать jimp для обработки изображений в Java.
public static void main(String[] args) < final NodeJS nodeJS = NodeJS.createNodeJS(); final V8Object jimp = nodeJS.require(new File("path_to_jimp_module")); V8Function callback = new V8Function(nodeJS.getRuntime(), new JavaCallback() < public Object invoke(V8Object receiver, V8Array parameters) < final V8Object image = parameters.getObject(1); executeJSFunction(image, "posterize", 7); executeJSFunction(image, "greyscale"); executeJSFunction(image, "write", "path_to_output"); image.release(); return null; >>); executeJSFunction(jimp, "read", "path_to_image", callback); while(nodeJS.isRunning()) < nodeJS.handleMessage(); >callback.release(); jimp.release(); nodeJS.release(); >
Подключение J2V8
Интеграция с Node.js уже доступна в J2V8 (версия 4.4.0). Вы можете использовать ее на Windows (32-х и 64-х разрядных), MacOS и Linux (64-х разрядных). Используйте следующую зависимость в pom, чтобы получить ее из Maven Central (этот пример для Windows 64-х, не забудьте поменять для других платформ):
com.eclipsesource.j2v8 j2v8_win32_x86_64 4.4.0
От переводчика
J2V8 дает нам новый уровень абстракции, позволяющий выбрать наиболее подходящую технологию для каждой отдельной задачи в рамках целого проекта. Как разработчика меня всегда привлекала надежность Java и удобство Node.js. И, в скором времени, надеюсь, мы увидим примеры успешных проектов, сочетающих в себе лучшее из двух миров.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Call Java classes from javascript Node.js
cesarvr/Ella
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
Readme.md
Is an NodeJS native plugin to allow Java code execution inside V8/NodeJS container. Is done in C++11 to make use of object oriented design.
This library is compatible with Node.js 6 and below.
- Because Java have very good ecosystem of libraries like PDFBox, iText, Solr, etc. all mature and useful.
- The objective is to create wrappers around the library you want and use it in your Node app.
- Easing Node.js integration with legacy Java system.
- Performance, comunication between JS and a JVM method is ≈
- The JVM run in the same NodeJS process as a native add-on so comunication between each other is fast.
- Allow you to load jar/classes and use them inside NodeJS like Javascript objects literals.
- The API can choose the right method giving a set of arguments, so it solves the method overloading in Java. [experimental].
- Exception handling, exception thrown by JVM are translated to Javascript exception.
- You can send blocking Java calls to a background thread and assign a callback to continue when finished.
- This is part of the LibJNI project, but explain how the performance is achieved by using this broker class to hide the caching/reflection details to the object class, this server class can be easily replace by custom made or platform specific implementantion, you just need to implement the same method signature and thats it.
- support to static classes.
- support to non-void constructor.
- support for java.lang.object derivatives args/return.
- Primitive
- int
- java.lang.String
- double
- byte[] — to Buffer to handle binaries.
$ export JAVA_HOME=/jdk/location/ #finish with / is important here, there is a bug in the installer :( $ npm install ella
setClassPath ( path: string array, recursive: true)
path: array, paths where to find the .jars/.class
recursive: true/false, if true look for jar/classes recursively.
This method allow us to configure the classpath,
var ella = require('ella'); ella.setClassPath(['/folder/with/.jars/.class', . ], true); //if true flag, it will look recursively all jars/class.
return the classpath configuration.
This method allow us to configure the classpath.
ella.getClassPath(); //myjar1.jar:myjar2.jar
create an JVM instance asynchronously.
callback(instance): function take as parameter an instance of the JVM.
This method allow us to configure the classpath.
ella.start(function(vm)< /* do some work with vm */ >)
vm.new (string qualified classname)
given a classname create a new object.
var stringBuffer = vm.new('java.lang.StringBuffer'); // stringBuffer.append // stringBuffer.insert // stringBuffer.substring // .
To make an sync call just call the method.
stringBuffer.append('hello'); console.log(stringBuffer.toString() ); //hello.
Just call the method as normal and add a function callback as an extra parameter this extra parameter transform the call to async.
var pdf = vm.new('com.pdf.Library'); // method signature byte[] createPDF(string); var buffer = pdf.createPDF('my_blocking.pdf'); // this call will block the interpreter in this position. // the addition of an anonymous function make all jvm->js-method async. pdf.createPDF('my_async.pdf', function(buffer)< /* do some work with buffer */ >); // non-blocking call. //js code.
About
Call Java classes from javascript Node.js