📜  如何在 Node.js 和浏览器之间共享代码?

📅  最后修改于: 2022-05-13 01:56:24.416000             🧑  作者: Mango

如何在 Node.js 和浏览器之间共享代码?

在本文中,我们将探讨如何编写可供客户端和服务器端应用程序使用的 JavaScript 模块。
我们有一个带有 JavaScript 客户端(在浏览器中运行)和与之通信的 Node.js 服务器的小型 Web 应用程序。我们有一个函数getFrequency() ,服务器和客户端都可以使用它来获取给定字符串中字符的频率。我们希望创建一组可以促进两端任务的方法。
方法:
为客户端(在浏览器中运行)编写代码与服务器端 Node.js 应用程序有很大不同。在客户端,我们主要处理 DOM 或 Web API,如 cookie,但这些东西在 Node.js 中不存在。我们不能在客户端使用节点模块的其他原因是节点使用CommonJS模块系统,而浏览器使用具有不同语法的标准ES 模块
在节点中,我们使用 module.exports 来公开功能或属性。但是,这会在浏览器中中断,因为浏览器无法识别export 。所以,为了让它工作,我们检查是否定义了导出,如果没有,那么我们创建一个合理的对象来导出函数。在浏览器中,这可以通过创建一个与模块同名的全局变量来实现。
模块的结构如下所示:
示例模块.js

javascript
// Checking if exports is defined
if(typeof exports === 'undefined'){
   var exports = this['sampleModule'] = {};
}
  
// The code define the functions,
// variables or object to expose as
// exports.variableName
// exports.functionName
// exports.ObjectName
  
// Function not to expose
function notToExport(){ }
  
// Function to be exposed
exports.test(){ }


javascript
(function(exports) {
    
   // The code defines all the functions,
   // variables or object to expose as:
   // exports.variableName
   // exports.functionName
   // exports.ObjectName
  
}) (typeof exports === 'undefined'? this['sampleModule']={}: exports);


javascript
// All the code in this module is
// enclosed in closure
(function(exports) {
  
    // Helper function
    function toLC(str) {
        return str.trim().toLowerCase();
    }
  
    // Function to be exposed
    function getFrequency(str) {
        str = toLC(str);
        var freq = [];
        for(var i = 0; i < 26; i++) {
            freq.push(0);
        }
  
        for(var i = 0; i < str.length; i++) {
            freq[str.charCodeAt(i)-97]++;
        }
        return freq;
    }
  
    // Export the function to exports
    // In node.js this will be exports
    // the module.exports
    // In browser this will be function in
    // the global object sharedModule
    exports.getFrequency = getFrequency;
      
})(typeof exports === 'undefined'?
            this['sharedModule']={}: exports);


javascript
// Simple node.js script which uses sharedModule.js
  
// Get module.exports of sharedModule
const utilities = require('./sharedModule');
  
// Print frequency of character
console.log(utilities.getFrequency("GeeksForGeeks"));


javascript
// Use functionality getFrequency which
// is available in sharedModule object
document.write(this.sharedModule.getFrequency("GeeksForGeeks"));


html



上述格式有一个问题,我们在sampleModule.js中定义但未导出的任何内容都将可供浏览器使用,即函数notToExport() 和 test() 都将在此文件之外工作。因此,为了克服这个问题,我们将模块包装在一个闭包中。
示例模块.js

javascript

(function(exports) {
    
   // The code defines all the functions,
   // variables or object to expose as:
   // exports.variableName
   // exports.functionName
   // exports.ObjectName
  
}) (typeof exports === 'undefined'? this['sampleModule']={}: exports);

示例:让我们制作一个示例模块,其中包含一个方法“getFrequency”来计算字符串中字符的频率。

  • sharedModule.js

javascript

// All the code in this module is
// enclosed in closure
(function(exports) {
  
    // Helper function
    function toLC(str) {
        return str.trim().toLowerCase();
    }
  
    // Function to be exposed
    function getFrequency(str) {
        str = toLC(str);
        var freq = [];
        for(var i = 0; i < 26; i++) {
            freq.push(0);
        }
  
        for(var i = 0; i < str.length; i++) {
            freq[str.charCodeAt(i)-97]++;
        }
        return freq;
    }
  
    // Export the function to exports
    // In node.js this will be exports
    // the module.exports
    // In browser this will be function in
    // the global object sharedModule
    exports.getFrequency = getFrequency;
      
})(typeof exports === 'undefined'?
            this['sharedModule']={}: exports);
  • nodeApp.js

javascript

// Simple node.js script which uses sharedModule.js
  
// Get module.exports of sharedModule
const utilities = require('./sharedModule');
  
// Print frequency of character
console.log(utilities.getFrequency("GeeksForGeeks"));
  • 客户端应用程序.js

javascript

// Use functionality getFrequency which
// is available in sharedModule object
document.write(this.sharedModule.getFrequency("GeeksForGeeks"));
  • 索引.html

html



运行程序的步骤:

  • 复制并粘贴所有代码及其各自的文件名,并确保所有文件都在同一目录中。
  • 在同一目录中打开终端并执行'node nodeApp.js'
  • 在任何浏览器中打开index.html

输出:

  • node.js 控制台上的输出:
[ 0, 0, 0, 0, 4, 1, 2, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0 ]
  • 浏览器上的输出: