如何检测脚本是否在浏览器或Node.js中运行?

我有茉莉花testingspec文件,我想运行它使用node.js和浏览器。 如何检测脚本是否在节点中运行?

一些想法:

你可以检查窗口的全局对象,如果它是可用的,那么你在浏览器中

if (typeof window === 'undefined') // this is node 

或者你可以检查过程对象,如果它是可用的,那么你在节点

 if(typeof process === 'object') // this is also node 

你检查exportsvariables,如下所示:

 if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = { ... }; }