简体   繁体   English

在 Node.js 中运行浏览器 JS

[英]Run browser JS in Node.js

I wrote some basic javascript code in AngularJs.我在 AngularJs 中编写了一些基本的 javascript 代码。 I want to be able to run this code in Node.js but keep the possibility to run it in the browser depending the situation.我希望能够在 Node.js 中运行此代码,但可以根据情况在浏览器中运行它。

I know that it is possible do run Node.js code in the browser by using browserify or lobrow but I did not find a solution to run browser code in Node.js我知道可以使用 browserify 或 lobrow 在浏览器中运行 Node.js 代码,但我没有找到在 Node.js 中运行浏览器代码的解决方案

Thanks in advance for your answers预先感谢您的回答

Daniel丹尼尔

First a warning.首先是警告。 NO DOM manipulation in your module since node has no DOM.模块中没有 DOM 操作,因为节点没有 DOM。 Also if you need to require anything in your module you really should be looking at Browserify et al.此外,如果您需要在模块中require任何内容,您确实应该查看 Browserify 等。

Your module would look like this你的模块看起来像这样

(function(){
    var sayHello = function(name) {
       return "Hello " + name;
    };

    // here's the interesting part
    if (typeof module !== 'undefined' && module.exports) {  // we're in NodeJS
        module.exports = sayHello;
    } else {                                                // we're in a browser
        window.sayHello = sayHello;
    }

})();

In node在节点

var sayHello = require('./myModule');
console.log(sayHello("Node"));        // => "Hello Node"

and in your browser并在您的浏览器中

<script src="myModule.js"></script>
<script>
  console.log(sayHello("Browser"));   // => "Hello Browser"
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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