欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

nodejs 使用 js 模塊的方法實(shí)例詳解

 更新時(shí)間:2018年12月04日 11:02:28   作者:Love it or leave it  
這篇文章主要介紹了nodejs 使用 js 模塊的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下

Intro#

最近需要用 nodejs 做一個(gè)爬蟲(chóng),Google 有一個(gè) Puppeteer 的項(xiàng)目,可以用它來(lái)做爬蟲(chóng),有關(guān) Puppeteer 的介紹網(wǎng)上也有很多,在這里就不做詳細(xì)介紹了。 node 小白,開(kāi)始的時(shí)候有點(diǎn)懵逼,模塊導(dǎo)出也不會(huì)。

官方文檔上說(shuō)支持 *.mjs 但是還要改文件擴(kuò)展名,感覺(jué)有點(diǎn)怪怪的,就沒(méi)用,主要是基于js的模塊使用。

模塊導(dǎo)出的兩種方式#

因?yàn)閷?duì) C# 比較熟悉,從我對(duì) C# 的理解中,將 nodejs 中模塊導(dǎo)出分成兩種形式:

1.一個(gè)要實(shí)例化才能調(diào)用的模塊
2.一個(gè)不需要實(shí)例化就可以調(diào)用的靜態(tài)類,提供一些靜態(tài)方法

•導(dǎo)出一個(gè)要實(shí)例化的類

module.exports = exports = function (){ };
module.exports = exports = function() {
 this.syncCompanyList = async function(developerName){
   await syncCompanyInfo(developerName);
 };
 async function syncCompanyInfo(developerName){
   // ...
 }
}

•導(dǎo)出一個(gè)靜態(tài)類

exports.funcName = function (){};
var getDistrictCode = function (districtName) {
  if (districtName) {
    for (let i= 0; i< DistrictInfo.length; i++) {
      let district = DistrictInfo[i];
      if (district["name"] == districtName || district["aliasName"] == districtName) {
        return district["code"];
      }
    }
  }
  return "";
};
var getNormalDistrictName = function (districtName) {
  if (districtName) {
    if (districtName.indexOf('區(qū)') > 0) {
      return districtName;
    }
    for (let i= 0; i< DistrictInfo.length; i++) {
      let district = DistrictInfo[i];
      if (district["name"] == districtName || district["aliasName"] == districtName) {
        return district["name"];
      }
    }
  }
  return "";
}
// 設(shè)置導(dǎo)出的方法及屬性
exports.getDistrictCode = getDistrictCode;
exports.getNormalDistrictName = getNormalDistrictName;

引用導(dǎo)出的模塊方法#

在 node 里使用 require 來(lái)引用模塊

•引用 npm 包

const log4js = require("log4js");

•引用自己編寫(xiě)的模塊

const districtUtil = require("./utils/districtUtil");

使用導(dǎo)出的模塊#

要使用某一模塊,需要先引用某一模塊,引用模塊可以參考上一步

•實(shí)例類

const company = require("./company");
// ...
// 實(shí)例化一個(gè) company 對(duì)象
var comp = new company();
// 調(diào)用 company 里的 syncCompanyList 
comp.syncCompanyList ();

•靜態(tài)類

const districtUtil = require("./utils/districtUtil");
// ...
// 調(diào)用 districtUtil 里的 getDistrictCode
let districtNme = districtUtil.getDistrictCode('districtName');

總結(jié)

以上所述是小編給大家介紹的nodejs 使用 js 模塊的方法實(shí)例詳解,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論