-2

I have a frontend in HTML and JAVASCRIPT. I need to get value from nodejs file and display it in HTML label. So I create new node js file node.js as:

const Web3 = require('web3');
const web3 = new Web3('https://kovan.infura.io');

web3.eth.getBalance('0x9E632F36D8193a23ee76e7C14698aCF4b92869A2').then(console.log);

I include this file in script tag as:

 <script src="node.js"></script>

First I want to look output in the console but it is giving an error

Uncaught ReferenceError: require is not defined

So, I try this code directly in HTML file within the script tag without including node file but still gives the same error. Can somebody help me with this? I am new to use all this together.

Varsh
  • 413
  • 9
  • 26
  • 2
    Here's a good explanation why https://stackoverflow.com/a/9901097/9172668 – sassy_rog May 06 '19 at 07:40
  • 1
    You can't use node stuff from front-end files like that. You have to make a node server that creates the files with the required information, with EJS templates for instance. Basically node stuff is only available on the server, not in the browser. – madprops May 06 '19 at 07:41
  • I understand why is this problem. But how to solve this? – Varsh May 06 '19 at 08:03

1 Answers1

-1

Somehow, I managed to find a solution. I used browserify, which makes easy for me to run the nodejs code from my web app. Browsers don't have the require method defined, but Node.js does. With Browserify you can write code that uses require in the same way that you would use it in Node.

browserify will recursively analyze all the require() calls in your app in order to build a bundle you can serve up to the browser in a single tag. I referred this link: http://browserify.org/

Varsh
  • 413
  • 9
  • 26