Vishwa Iyer
Vishwa Iyer

Reputation: 861

Import NodeJS file in regular JavaScript file

I have 3 files, an index.html, a Learner.js, and a bot.js. Right now, the bot.js is a regular js file that I load in the html file with <script> tags, and the Learner.js is a NodeJS file. The only reason I have this file is because I want to use a Neural Net library but it only works with NodeJS, not regular javascript, so how exactly would I reference any functions, varibles, etc. in my bot.js that exist in Learner.js, should I load the file using <script> tags, or what's the best way to go about this?

Upvotes: 0

Views: 211

Answers (3)

Dario
Dario

Reputation: 4035

You can add it simply:

<script type="text/javascript" src="Learner.js"></script> 
<script type="text/javascript" src="bot.js"></script> 

But, if your Learner.js javascript file use some native node.js engine functions or simply require() calls, it wont work.

In this case, consider to try to use Browserify or similar tools, to allow run nodejs specific stuff into the browser.

All these tools have limitations, not all code can be executed browser side.

When it is not possible you have to implement a web service server in nodejs (for example using a REST api, JSON over RPC pattern, ...) to allow execute the code and get the result in the browser.

Upvotes: 1

Jared Smith
Jared Smith

Reputation: 21926

The answer is that its (potentially) complicated.

There are things that node.js can do that browser JavaScript cannot do (like have filesystem access), and things that the browser doesn't do (e.g. Buffer API, module system). Obviously the later can be brought to the browser by libraries, but on the former you're out of luck.

So the question is, what node-specific stuff does that library use? If its just require use webpack/browserify or a babel/rollup plugin. But you're going to have to comb through that library to see what its actually using and whether or not that would be present in the browser.

Upvotes: 1

Luzan Baral
Luzan Baral

Reputation: 3698

As long as both are JavaScript and have variables that have global scope, a variable from Learner.js can be used in bot.js is Learner.js is loaded before bot.js

<script type="text/javascript" src="Learner.js"></script> 
<script type="text/javascript" src="bot.js"></script> 

You could also use a property of window or (in the global scope) this to get the same effect.

But When you are using node you'll have to make sure you are also running the node server and best way to get outputs are by sending json object by use of some API, and get that json response in bot.js

Upvotes: 0

Related Questions