This question already has answers here:
Call java program from Node.js application
(5 answers)
Closed 2 years ago.
I am trying to call a function defined in a java from node js .
Example :
public class A{
public void show(){
System.out.prntln("Invoked from Node JS");
}
}
and a node js file
console.log("In Node JS");
//define calling A like A a = new A();
a.show();
I may be totally wrong but I am trying to access a java function from node js .
This is a great question. In general, there are several approaches to language inter-operation:
Running code in completely separate, isolated programs / processes, and using interprocess communication (IPC) or other networking protocols (TCP or higher level protocols built on top of TCP like HTTP, often with a REST-ful API, or some form of RPC system) to send information between the two processes that have been written in different languages.
"Transpiling" one language into the other (e.g. using the JSweet or TeaVM transpilers to convert Java code to JavaScript code), and then creating a single application / process out of the original code in one language together with the transpiled code from the other language (which is now in the same language as the other code being built into that final application).
Using a common intermediate language and low-level "native" interfaces that allow the code to interoperate. Most languages have some form of interoperation with C (because C is a common denominator supported by most operating systems). While this would not work with client-side JavaScript (though some of the principles are still be relevant with Native Client (NaCL)), with NodeJs, you can call into C code using node-gyp and cwrap. Once you are in C land, you can call into Java using the Java Native Interface (JNI) (though making it possible to call your Java code from C using JNI is probably more easily accomplished by letting SWIG autogenerate much of the boilerplate for this for you, rather than directly writing to the JNI specification).
As with all things, there are tradeoffs to the various approaches:
Approach #1:
Pros:
relatively straight-forward
works with almost any programming language
each subsystem is fully isolated from the other
each system can be debugged in a language idiomatic manner
Cons:
must define shared protocol
can result in redundant, duplicated code
protocols must be kept in sync
changes must be backwards-compatible or it will break
NOTE: protocol buffers can help with this
serialization/deserialization overhead
channel can add other overhead (e.g. if communicating between processes over the Internet as opposed to on the same machine via a UNIX domain socket)
must consider security of communication mechanism
encryption of data between subsystems
access control of the endpoints
Approach #2:
Pros:
no serialization/deserialization overhead
can debug final system using idioms for target language
Cons:
not all languages can transpile from one to the other
even if a transpiler supports the two languages:
often supports only a subset of the language
may need to fix/modify code to allow it to transpile
may need to fix/modify the transpiler
slightly different semantics in transpilation can lead to subtle, surprising bugs
no isolation between the subsystems
Approach #3:
Pros:
no serialization/deserialization overhead
more support than approach #2
no need to rewrite original code in either language
Cons:
must become an expert in esoteric tools like SWIG
result is very difficult to debug
stacktraces for NodeJS code suddenly contain C, JVM, Java code
debugging tools don't easily span languages (e.g. may end up stepping through JVM code interpreting Java, rather than stepping through the actual Java code)
ownership of objects, garbage collection across languages can lead to surprising / difficult to handle bugs if ownership semantics not correctly encoded
different threading models between languages or other semantic mismatches between languages can make entire system buggy / difficult to debug
Having used systems with approach #1 and approach #3 (as well as hearing of systems using approach #2), I would strongly recommend using approach #1 wherever possible; only if you find the serialization overhead to be untenable (and you are not able to optimize the communication protocol / mechanism to handle that problem) would I venture into the other waters. That being said, approach #2 can be successful if the languages are very similar (like transpilation from TypeScript to JavaScript), and approach #3 can be successful if the use of this mechanism is very limited in scope (e.g. just need to expose one small but frequently called / performance-sensitive function this way).
I know very little about java but can't you use a node-java bridge?
https://github.com/joeferner/node-java
I think this is use node-gyp so likely works along the line of #3
If your method is public static void main, you can use node-java-caller
Related
I saw those javascript front-end build tools, e.g. webpack, using the word "compile" from time to time. I am not sure what does compile javascript codes mean exactly, at least not like compile c/c++ codes.
I think I understand the "build" process in general, like bundle all js codes into one big file, minify/uglify the codes, using babel to transforms ES6 syntax(transpile). But what does compiling mean here, how does it fit in the whole building process or it is just another name for the whole build process?
Currently, I thought it may be just another name for using Babel to transforms ES6 syntax.
PS. after reading this SO Is Babel a compiler or transpiler? I believe my question is not same as that. Because it is not just related to Bable. For example, webpack also uses the term compiler https://webpack.js.org/api/compiler/ I do not understand its meaning there!
Browserify uses compiler as well e.g, https://github.com/robrichard/browserify-compile-templates "Compiles underscore templates from HTML script tags into CommonJS in a browserify transform"
It's better to describe the process as "transpilation."
Javascript always executes in a specific environment: in Chrome and Electron, it's the V8 engine; in Firefox, it's SpiderMonkey; etc. Each of these engines supports a specific set of language features and not others. As an example, some engines only support var and do not support const or let. Some support async/await, and others only support Promise.
But web developers know about these other features, and they want to use them, even when they're writing for an engine that doesn't support those features. Why? Most new language features are designed with the goal of making it possible to express complicated concepts in simpler and cleaner ways. This is extremely important, because the number one job of code is to make its purpose clear.
Thus, most language features are essentially syntactic sugar for existing functionality. In those cases, it's always possible to express a routine using both new and old syntax. This is a logical necessity.
A transpiler like Babel can read a script written using advanced syntax, and then re-express the script using a restricted set of language features. Relying on an intermediate representation called an abstract syntax tree, it can produce code that is guaranteed to be functionally equivalent, even though it does the work using very different, more widely-supported control structures.
Perhaps we web developers have gotten lazy in our terminology. When we talk of "compiling" javascript, we aren't usually talking about converting the script to something like bytecode. We're talking about transpilation.
Other kinds of build tasks are also becoming quite common. These days, the front-end is obsessed with a million flavors of "templating," because it's extremely tedious and confusing to describe DOM changes using pure javascript, and because application complexity is increasingly very rapidly. Some frameworks require you to convert source code to other intermediary forms that are later consumed by the web application at runtime. Others permit devs to describe UI using invented syntaxes that no browser is even attempting to support natively. Which tasks are needed varies by application depending on which frameworks are being used, the particulars of the application architecture, and the contours of the deployment environment, and that's just a start.
At its foundation, a web page is built using HTML, CSS, and javascript. That much hasn't changed. But today, most serious applications are built almost entirely in javascript (or something very much like it) and sass. Building the application is the process of applying a set of transformations to the source code to yield the final artifacts in those three bedrock languages.
We lump all that stuff under the term "compile."
You pretty much hit the nail on the head. When the Compile (or more appropriately transpilation) operation happens on a JavaScript project it can mean a number of things. As you mentioned these could range from minification, applying polyfills, shims, or the literal act of "compiling" the scripts into a single bundle file for platform/browser consumption.
Transpilation when using super sets of the JavaScript language such as TypeScript, ActionScript, or UnityScript describes the process of converting the source x-script back into native JavaScript which can be in turn be interpreted by a browser (since the browser doesn't recognize the superset languages).
However you are absolutely correct. We aren't compiling our JavaScript into binary, but the term gets thrown around a lot which can lead to confusion. All that said, we are closing in on the age of adoption of WebAssembly and ASMJs which promises to bring the age of bytecode running in the browser which will bring about some interesting possibilities, but alas... That's a story for another day ;)
You're right when you say these front-end Javascript tools don't use the word compile in same context in what your used to with build tools for languages like C/C++. C/C++ compilers turn source code into machine code.
These JavaScript build tools-- like Webpack-- use the word compile in a sense thats more metaphorical than conventional.
When web build tools use the word compile, they're using it in the sense that they are transpiling, minifying (a.k.a uglyfying), and bundling the source files so they are better optimized for client browsers and network requests. (Smaller file sizes, better browser compatibility, less HTTP requests from bundled assets, etc.)
There is c++ library and I need to make function calls to this library from JavaScript running on the browser on the client side, the library resides in the client machine only. How can I load the library and access the interfaces (functions) provided by the c++ library? The library contains algorithms and rendering calls mainly.
A few options I can think of:
1) Find a different library in JavaScript.
2) Port the C++ code over to JavaScript. How easy this is depends on
how complex the C++ code is or how much of it you need.
3) Wrap the C++ code in a web service on a server and call it using AJAX. I'm not personally familiar with any C++ web service frameworks, but barring that, you could create Java, Python, or .NET bindings for the library (or just for the portion that you need), or bindings in another language. Then you would write your web service in whatever language you chose.
3B) Alternative to #3 - If the library has a command-line interface, or if there exists a command-line program that uses the library, your web service could call that and you wouldn't have to write a language binding. Note however that there are performance & security problems to be aware of with this option.
4) If you have the C++ source code for the library, you could try to compile the library to JavaScript using Emscripten.
I would probably try those in that order, roughly. I might try #3 last cause it could be the trickiest.
Also, if you do #3 or #3B, you'll want to be sure your use of the library is thread-safe.
Disclaimer: I've never tried any of these except #3B.
You'd be better off creating a 'C' wrapper for the C++ library and calling that from the Javascript.
C++ is notoriously difficult to interface with due to the language standard lacking a tight ABI definition. C does not have this limitation. For this reason, 'C' ends up being the lingua franca when you want two programming languages to talk with each other.
Usually browsers doesn't allow that, because that's very insecure.
You might compile C++ in asm.js and use it as JavaScript library.
Alternatively you can create browser extension, which will run or call desired code.
Yes its possible but before you can call them from javascript. You do this by creating an interface file to tell javascript about the interface.
I have some C++ code that I want to expose to client side of a web app. Ideally, I want to write Javascript wrapper objects for my C++ classes so that I can use them clientside.
Has this been done before?. Does anyone have a link to show how this may be achieved?
There is a library to convert C++ code to javascript, it might help:
emscripten
Libjspp C++ template based wrapper for embedding and extending Javascript engine spidermonkey 1 . 8 . 5 and more
SpiderMonkey? is Mozilla Project's Javascript/ECMAScript engine.
Libjspp allows C++ developers to embed SpiderMonkey? simply and easily into their applications. Libjspp allows to run multiple Javascript Engines within same process which suits one engine per thread para dime which is helpful in achieving true parallisim. Also Libjspp no way stops user from running multiple threads within engine.
http://code.google.com/p/libjspp/
I guess that RPC is what you want. You'll need to wrap your functions on the server side using some sort of framework. I've not yet used it, but this one looks promising.
On the client side you use proxy objects to dispatch the function calls. The communication is handled usually either via XML-RPC or JSON-RPC. I used this client side framework and was quite content but I'm sure you'll find many others.
This is an old topi, however, I was in the exact situation right now, and all of the solutions I found on the net complicated or outdated.
Recently, I ran across a library which supports V8 engine (including the new isolation API, which makes 90% of the libraries I found outdated) and provides great exposure and interaction API.
https://github.com/QuartzTechnologies/v8bridge
I hope that my solution will help anybody.
There's a relatively new library for doing this called nbind. Maybe that would suit you? It looks very good to me, and I'm just about to start using it.
I think you want a C++ JSON parser. You should be able to find one here http://www.json.org/. It may not do all you want because it just serializes and deserializes C++ objects without any behavior, but it should be good enough. See https://stackoverflow.com/questions/245973/whats-the-best-c-json-parser for some discussion.
If the C++ code has to be on the client, then there is no simple way to do this for a web app. A solution may involve coding plugins for the browsers you want to support, which may then be accessed from javascript code.
If, for example, you need this for a client application, that is another case. Such a thing has been done and involves linking your application to (or running from outside) with for example chromium library, or any other javascript execution engine. That way you can create bindings to C++ classes and use such objects from javascript and vice-versa. Note that this is also not a trivial solution and may be a big effort to implement (also requires additional resources).
You could for example wrap the C++ classes in PHP or Python, and then implement an API over HTTP to access the required functions.
Or if you insist on exposing the functions as JavaScript you could try using Node.js, and create an C++ add-on to wrap you classes. See the Node.js documentation here: http://nodejs.org/api/addons.html#addons_wrapping_c_objects
But either way, I don't think avoid creating some sort of API (HTTP SOAP, XML RPC) to access the functions on your server.
Though QML is not exactly Javascript, Qt is not plain C++, but what they do together seem just like what you need
Disclaimer: This question will be a bit open-ended. I also expect replies to be partly based off of developer preference.
I've been doing some research lately on Express.js (coupled via Node.js) and I'm struggling to find how I would fit either of these technologies into my current workflow for developing websites. Lately I've been working in either Wordpress or Ruby on Rails, the prior will run on Apache, the latter will run on it's own proprietary server (I assume).
Now perhaps I'm just not understanding something, but I fail to see the advantages to enlisting the support of a Javascript-based framework/server. If there are clear cut advantages to making this part of my workflow, what would they be? I haven't been able to find any ways to fit this into (per say) a Rails application or a Wordpress site. Could someone point me in the direction of some better help of implementing these technologies on top of ones I already use?
One last question, what happens if someone has Javascript disabled in their browser? How would a Javascript-based server react (if at all)?
There are two big differences:
Event loop
Node.js is a bit different from the usual Apache concept, because of the way it handles connections. Instead of having synchronous connections, Node uses an event loop to have non-blocking operations. Note that this is not unique to Javascript and there are C and Python based frameworks that also enable a similar event loop approach, however in Javascript it's probably the most natural feeling since this is how JS has worked since it was introduced.
Supposedly, this should enable you to handle more concurrent clients. However, it hasn't had as much real world exposure as the regular blocking solutions so this approach isn't as mature as most current implementations. The actual performance difference is questionable as it depends on the exact requirements for the application.
Code Sharing
This point is much less controversial than the previous difference, but in essence if you have the same language on both the client and the server, you can reuse a lot of the code, instead of having to rewrite your data structures etc in multiple languages, saving you a lot of development time. However, you have to understand that the concepts of server side JS are different from what you know on the browser, such as you don't have dynamic JS with jQuery or Prototype, but it's result and use-cases are more similar to what PHP is widely used for.
The primary advantage of having Javascript as your server-side language is that you're writing your whole system in a single language.
This has advantages in terms of:
Learning curve and mental context switching for the developer
and also in provides some possibility for sharing code between the two environments.
However, this last point is less helpful than it sounds, for a number of reasons, and this is where the disadvantages come in:
Not much code can actually be shared, because of the differences in what the two environments are actually doing. Maybe a bit of validation code, so you know that you're doing the same checks on both client and server, and maybe a few utility functions, but that's about it.
The libraries you use will be completely different between the two as well: jQuery only works on the client, and Node has libraries that are server-specific.
So as a developer, you still need to mentally context switch between environments, because the two environments are different. They may share a language, but their modes of operation are different, and what they do is different. In fact, sharing the language between the two can actually make it harder to context switch, and this can lead to errors.
Finally, it's worth bearing in mind that while Node is getting lots of attention from the developer community, it is still new and evolving quickly: if you're a business considering a it as a development platform, it's probably not quite yet stable enough to base a major project on.
Html can contain little bits of Javascript embedded in it (e.g. defined in onclick event handlers).
If I were writing an Html browser using a dotNet language like C#, what technologies or APIs could I use to run such Javascript fragments, given that I don't receive it until run-time (and receive it as string data, not as executable code)?
Is it any easier or harder if the code to be run were C# snippets rather than Javascript?
Is there any technique which doesn't require my code to have unusual priviledges? For example, a method like CodeCompiler.FromSource requires SecurityPermissionFlag.UnmanagedCode (which seems to me excessive: I don't see why it's so risky to compile code).
If I controlled the server-side as well as the client-side code, I could also consider compiling such script fragments on the server instead of on the client, and then sending it as precompiled code to the client side to be executed. Is there a way to send such code (a dotNet assembly, presumably) over the network to the client, have client-side code receive it from the network into client-side RAM, and invoke it on the client side without storing it as a file on a client-side disk drive?
Edit
I have answer to the first three questions: I've resigned myself to the fact that compiling takes high privileges. I don't see why; maybe (although I don't find this a very convincing reason) it's because the compiler is implemented using unmanaged code. Maybe this will change when they reimplement the compiler using managed code, in maybe the "C# version 5" timeframe. In any case, whatever the reason, that seems to be the way it is, and there are no work-arounds (other similar APIs but which require fewer privileges).
My remaining question then is how to get an Assembly instance from one machine to another. When I have time I'll find out whether untrusted code can run the Assembly.Load(byte[] rawAssembly) method.
Server side Javascript is one of the languages supported by the .NET platform. I used it many times in the scenrios when you need to insert small code snippets into existing code. Runtime it can be loaded from i.e. database and compiled, so there is no preformance penalty.
From the standpoint of making the plumbing work (retrieveing the source, compiling it, etc.) there is no difference. With strongly typed languages though it is much more difficult to assemble code snippets into a compilable compilation unit.
Permissions is certanly a challenge. I am not sure about the specific permission you mentioned, but security is a concern, after all the source you compile can be anything and if you are not careful about the source of your code it can become the backdoor into your system
The answer to this one is - yes of course. You can load an assembly from anywhere, not necessarily from a file, you can also compile in memory - that's what I do. There is no dll file in this case.
You're asking several questions, sort of, so I'll give you an idea on one of them.
There's a very good article and some code samples from:
http://www.west-wind.com/presentations/dynamicCode/DynamicCode.htm
which talks about compiling and executing C# code at runtime. I found it very useful and I am using this in a standard c# application. Seems like it would be usable for your problem as well.