简体   繁体   中英

JavaScript - how to inject different implementation of function e.g. alert (sharing modules with web & Node.js server side)

Situation: There is big number of JavaScript files. I want to run them on Node.js.

But there are several places where eg alert() is used, that causes Node.js to fail.

Of course, there is way to look into every file and add import like

alert = require('console').log

but that would stop those files working inn browser (on client side).

Is there way to inject different implementation of alert ? That is to change/add function implementation without modifying sources?

在代码的开头,编写:

global.alert = console.log;

Basic version

Inside a file silentalert.js

if(typeof global != "undefined"){
  global.alert = typeof console != "undefined" && console.log ? console.log.bind(this) : function(){};
}

Inside your NodeJS scripts:

require('./silentalert');

This code will print alert messages to console.log in NodeJS but will still use alert when run in the browser.

The next implementation offers a more generic approach.


Cross-platform version

Inside a file silentalert.js

var g           = typeof global != "undefined" ? global : (typeof window != "undefined") ? window : {};
var c           = typeof console != "undefined" && console.log ? console.log.bind(this) : function(){};
var _old        = g.alert;
var silentalert = function(activate){
  g.alert       = activate ? c : _old;
};
if(typeof module !== "undefined"){module.exports = silentalert;}

Inside a NodeJS script:

var silentalert = require('./silentalert');
silentalert(true); 
// or silentalert(typeof window == "undefined") if you just want to silent alert() on NodeJS
// your script...
silentalert(false);

You can even directly include silentalert.js inside an HTML page:

<script src="./silentalert.js" type="text/javascript"></script>
<script type="text/javascript">
silentalert(true);
// your script...
silentalert(false);
</script>

Note: If you need to support IE8 .bind won't be available in that case replace:

var c = typeof console != "undefined" && console.log ? console.log.bind(this) : function(){};

with

var c = typeof console != "undefined" && console.log ? function(){console.log.apply(console, arguments);} : function(){};

Both scripts allows you to silent alerts in NodeJS while still being able to use them on the client-side.

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