Problems starting node.js in browser

I am trying to run an application with the node.js functions of my browser. I checked in the terminal and my javascript file, which includes the node.js functions, works well. However, when I run the html file that is connected to the javascript file, the browser returns an error stating that the require function is not defined. I understand that this is due to the fact that the browser cannot start node.js alone

The node.js code I'm trying to run is accessing the Watson api visual recognition:

var watson = require('./node_modules/watson-developer-cloud'); watson.visual_recognition({ username : '49f5d504-9387-45c6-9fda-9b58a9afc209', password : 'IITqAn0VPaFr', version : 'v2-beta', version_date : '2015-12-02' }).listClassifiers({}, function(err, response) { if (err){ console.log(err); } else { console.log(JSON.stringify(response, null, 2)); } }); 

I know that I have all the necessary files, because the file works in the terminal. Therefore, I continued to include:

 <script src ="https://cdn.socket.io/socket.io-1.4.5.js"></script> 

in my index.html before attaching my javascript file.

However, my javascript file still returns the same error that the require function is not defined. Am I doing something wrong? Is there a way to run this javascript file in a browser with node.js, but in particular without using a browser (which caused some directory problems in the past)?

+2
source share
2 answers

While Node and the browser run JavaScript (ECMAScript), this does not mean that the environment is the same.

In particular, a lot of APIs and globals are available in the browser that are not available in Node (document, window, etc.) and other global and APIs that are in Node that are not available in the browser (required, etc. .)

To execute code that uses Node specific global variables, such as require() , you need to define something and polyfill for you. This is something that does something like webpack or browser or systemjs. Even then, you need to make sure that the module you enter will be launched in the browser.

+2
source

The browser does not (yet) have any embedded modular system such as nodejs. If you want to use modules, for example in node, consider browserify or requirejs .

0
source

All Articles