簡體   English   中英

javascript 新手:從 index.html 調用 node.js 模塊

[英]New to javascript: Call a node.js module from index.html

我一直在關注我在網上找到的關於如何從 HTML 文件調用 node.js 模塊的示例。 我真正想做的是學習如何在 Web 應用程序中使用 API。 我正在嘗試使用 Zillow API。

這是我正在使用的示例: 示例:讓我們制作一個示例模塊,其中包含一個方法“getFrequency”來計算字符串中字符的頻率。

共享模塊.js

// 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); 

節點應用程序

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

客戶端應用程序.js

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

我遇到的問題是 clientApp.js 文件。 當我寫document.write(this.我在智能感知中沒有看到模塊 sharedModule 。似乎 clientApp.js 對 sharedModule 一無所知,所以我必須遺漏一些東西。

我在 windows 10 機器上使用 VS Code 作為我的編輯器。

要理解為什么會發生這種情況,您需要了解 JavaScript 中的作用域和 nodejs 中的模塊的概念。 VSCode 的智能感知可以獲取utilities變量的屬性,因為它在nodeApp.js文件的范圍內。 這是因為它是使用 node 非常有趣的require函數“導入”的。 這與clientApp.js文件不同。 它的全局范圍沒有直接鏈接到sharedModule.js文件的全局范圍。 該HTML文件,鏈接他們只是在運行時這樣做,直到出現這種情況,VSCode的智能感知不知道的是, sharedModule對象存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM