Passing data between javascript - javascript

Want to link one javascript file in index and exports it function to another javascript file
Index.html
<script src="test.js"></script>
test.js
var config = {};
config.server_ip = "127.0.0.1";
module.exports = config; //Error, module not defined
console.log("Hello World, I should be showing up in chrome console");
show.js
var config = require('./test');
console.log(config);
I want to run index.html and at the same time using node.js to run my show.js file.
Apparently I can only choose one, if I do not export, my console.log works, if i export, my console.log do not work.
Is there any other method to pass data like this?
Do note that the workflow has to be like this, and I do not want to link 2 javascript file into my index.html
I tried using import and export function via mozila guide, however it seems that chrome does not support that as well.

I want to run index.html and at the same time using node.js to run my show.js file.
If you want to use NodeJS to run the JavaScript, then you have to actually run it on NodeJS.
If you are loading the script through a <script> element in an HTML document then you are running it in the browser and not NodeJS (it is possible that you are using NodeJS to run a webserver that supplies the .js file to the browser as a static file, but that isn't the same as running it on NodeJS).
console.log("Hello World, I should be showing up in chrome console");
If you want to display something in the Chrome console then you need to run it browser-side and not in NodeJS.
Browsers don't have native support for AMD style modules, so to use the approach you are taking you would need to add something like RequireJS.

Related

How to compile require statements?

I have the following require statements in my .js file which gets transpiled from ES2017, however, the browser still does not recognize these commands (require is not defined). How can I solve this?
this.e = require('../../e.js'),
this.a = require('../../a.js'),
this.cb = require('../../cb.js'),
Transpiling your code is not enough to make it work in a browser. You will need a build system like webpack to bundle your code into one (or multiple) files that you can include in your web app.
For example webpack can first transpile your code using babel and then bundle your whole app into 1 file which will run in the browser without a problem (as it won't have any require anymore).
Another solution you can use is type="module" in your script tag:
<script type="module" src="/my/app.js"></script>
app.js
import a from "../../a.js";
...

How to use Node.js packages within a client-side html document using browserify

I'm unable to use a node.js module on my website with broweserify. The example only shows how to run a javascript file that is separate from the .html file, not how to use the node.js module within the .html file. Seems like a trivial problem, but I'm unable to make it work.
Here's what I've done:
Initialized node.js & installed a package, npm i webtorrent-health as an example
Created require_stuff.js which consists of a single line: var WebtorrentHealth = require('webtorrent-health')
Run browserify: browserify require_stuff.js > bundle.js
Include package in my html document, e.g. <script src='bundle.js'></script>
Use the package somewhere in my document, e.g. like this: <script>webtorrentHealth(magnet).then(foobazbar())</script>
Despite bundle.js executing and seemingly defining webtorrentHealth, the script within the .html document fails with WebtorrentHealth is not defined. What am I doing wrong? How do I make it work? Thank you!
You're very close to what you want to achieve. In fact, your code bundle.js is inaccessible from outside (in your case the browser) due to browserify, but you can expose your module by writing at the end of your file require_stuff.js:
window.WebtorrentHealth = WebtorrentHealth;
Now you can use WebtorrentHealth in your document.

Require is not working for node-opcua

I want to load a local version of node-opcua with 'require' inside a HTML file, but it does not really work. The code snippet is the following:
<script type="text/javascript" src="path_to_require.js"></script>
<script>
var opcua = require(["path_to_node-opcua"]); <!-- Yes, the path is correct >
var client = new opcua.OPCUAClient();
...
When I execute the script I get the following error in the console:
Uncaught TypeError: opcua.OPCUAClient is not a constructor
Hence, var opcua is loaded correctly, but OPCUACluent is not, although the class is declared in a file that is present in the node-opcua folder called opcua_client.js under node-opcua\lib\client\
Sources:
The 'require' script from http://requirejs.org/docs/download.html#requirejs.
The node-opcua folder with the console command
npm install node-opcua.
node-opcua is not intended to run inside a browser as it relies on nodejs specific features such as filesystem access, crypto and so on.
You need to use browserify if you want to use that module in client. You will also need to look at how to use browserify with file system access (it can be done if paths are known ahead of time).

readFileSync is not a function

I am relatively new to Node.js and have been looking around but cannot find a solution. I did check the require javascript file and it does not seem to have a method for "readFileSync". Perhaps I don't have a proper require file? I had a hard time finding this file, everywhere talked about it but most people did not post where to get it.
I installed Node.js and have the require.js file. My current code is like this:
fs = require(['require'], function (foo) {
//foo is now loaded.
});
console.log("\n *STARTING* \n");
// Get content from file
var contents = fs.readFileSync("sliderImages", 'utf8');
I had a bit at first getting require to work however it seems to load the require JavaScript file. I have been following guides and I am not sure why I get this error:
Uncaught TypeError: fs.readFileSync is not a function
I have tried many fixes and cannot seem to figure this one out.
Node.js does not use Require.js. Require.js was built so that you could have asynchronous module loading on the client-side (in your browser).
Node.js uses CommonJS style modules. Your code using CommonJS would look like this:
var fs = require('fs');
console.log("\n *STARTING* \n");
var contents = fs.readFileSync("sliderImages", "utf8");
If we assume you saved this in a file called main.js you would then enter this command in your console (make sure you are in the same directory as the file):
node main.js
This code will not run in the browser. Node.js runs on the server. If you want to load a JSON file on the browser side then you'll need to load it using AJAX. There are numerous resources available to show you how to do this. Be aware that you must either run your page from a server or have a special flag enabled to load in files from the file system.
This error can arise if you write
const fs = import('fs');
in a Node module
but should write
import fs from 'fs';

Loading modules with require in Cordova

I am new to javascript trying out cordova which heavily makes use of the module require(). I went through some tutorials for this like here .
I tried out a very simple example from this tutorial and there is something missing it seems.
This is my html code.
<script>
var abc = require("js/greeting.js");
function mod() {
try{
var g = abc.sayHelloInEnglish();
console.log("reached the call");
document.getElementById("modl").innerHTML = g;
}
catch(err){
console.log("error is" + err.message);
}
}
</script>
<button onclick="mod()">click</button>
This is the code for my greeting.js
//var exports = module.exports = {};
exports.sayHelloInEnglish = function() {
return "HELLO";
};
exports.sayHelloInSpanish = function() {
return "Hola";
};
When I click on the button click, it gives an error that abc is not defined. Is there something I am missing here to use the module?
Thanks a lot.
Actually module.require is not for browser. You can't use it like you do right inside script-tag. The require is for node.js (server-side javascript).
If you want to use it inside a browser you should use preprocessing. For example you can use browserify.
To learn more - great 3 min video CommonJS modules
You cannot use require/module.exports natively in the browser. It is built into Node.js/io.js and can be run on the server.
If you want to use require()/CommonJS modules in the browser, look at RequireJS.
If you want to run Node/io.js code in the browser in general (including but not limited to require()/CommonJS), look at Browserify or webpack.
Since you say you are using cordova, my guess is that you don't really need require() at all. Just write your HTML/CSS/JavaScript like you would normally and use cordova to package it up. cordova uses require() a lot but that should not affect your app's code.
Now you can use this npm package
https://www.npmjs.com/package/cordova-import-npm
Import files from npm packages into your cordova www/ directory
automatically, upon cordova prepare, cordova build or cordova run, and
before anything else is processed.
Oftentimes we want to import the latest files available in npm
packages into our www/ directory in cordova projects. With this module
you can do it automatically without building your own scripts.
You could use define in require.js is a way of passing a function or the result of. I was struggling with cordova cause one needs to be very carefull the Code needs to be clean. Define will help you if you only need to put your result as a object or anything inside the defined function and call it at a later time.
// obj.js script
define(function(){
{name: "joe",
lastname:"doe"}
})
In the other script you only require the file and pass it to a variable. I guess you could even get rid of the inner brackets in obj script.
//other.js
var string = require(["obj"])
console.log(string.name) // joe

Categories

Resources