简体   繁体   中英

Problems running node.js in browser

I'm trying to run an app with node.js functions my browser. I checked in the terminal and my javascript file which includes node.js functions runs well. However when I run the html file which is connected to the javascript file the browser returns an error which says the require function is not defined. I understand that this is because the browser can't run node.js alone

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

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 I have all of the required files because the file runs in the terminal. Therefore I proceeded to include:

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

in my index.html before connecting 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 any way I could run this javascript file in the browser that has node.js but specifically without using browserify (which caused me some directory problems in the past)?

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

In particular, there are many APIs and globals available in the browser that aren't available in node (document, window, etc.) and other globals and APIs that are in Node that aren't available in the browser (require, etc.)

In order to execute code that uses Node specific globals like require() , something needs to define and polyfill those for you. That's exactly what something like webpack or browserify or systemjs does for you. Even then you need to make sure the module you are bringing in will run in a browser.

Browser doesn't have(yet) any build-in module system like nodejs. If you want to use modules, like in node, consider either browserify or requirejs library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM