zoukankan      html  css  js  c++  java
  • nodejs 使用 js 模块

    nodejs 使用 js 模块

    Intro

    最近需要用 nodejs 做一个爬虫,Google 有一个 Puppeteer 的项目,可以用它来做爬虫,有关 Puppeteer 的介绍网上也有很多,在这里就不做详细介绍了。 node 小白,开始的时候有点懵逼,模块导出也不会。

    官方文档上说支持 *.mjs 但是还要改文件扩展名,感觉有点怪怪的,就没用,主要是基于js的模块使用。

    模块导出的两种方式

    因为对 C# 比较熟悉,从我对 C# 的理解中,将 nodejs 中模块导出分成两种形式:

    1. 一个要实例化才能调用的模块
    2. 一个不需要实例化就可以调用的静态类,提供一些静态方法
    • 导出一个要实例化的类

      module.exports = exports = function (){ };

      module.exports = exports = function() {
      
        this.syncCompanyList = async function(developerName){
            await syncCompanyInfo(developerName);
        };
      
        async function syncCompanyInfo(developerName){
            // ...
        }
      }
      
    • 导出一个静态类

      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('区') > 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 "";
      }
      
      // 设置导出的方法及属性
      exports.getDistrictCode = getDistrictCode;
      exports.getNormalDistrictName = getNormalDistrictName;
      

    引用导出的模块方法

    在 node 里使用 require 来引用模块

    • 引用 npm 包

      const log4js = require("log4js");
      
    • 引用自己编写的模块

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

    使用导出的模块

    要使用某一模块,需要先引用某一模块,引用模块可以参考上一步

    • 实例类

      const company = require("./company");
      // ...
      // 实例化一个 company 对象
      var comp = new company();
      // 调用 company 里的 syncCompanyList 
      comp.syncCompanyList ();
      
    • 静态类

      const districtUtil = require("./utils/districtUtil");
      // ...
      // 调用 districtUtil 里的 getDistrictCode
      let districtNme = districtUtil.getDistrictCode('districtName');
      

    End

    希望你能有所收获

  • 相关阅读:
    【转载】NHibernate的hbm.xml的配置文件大全
    C#读取文本播放相应语音【转】
    Convert.ToInt32、int.Parse(Int32.Parse)、int.TryParse三者之间的区别
    to_date()与24小时制表示法及mm分钟的显示
    DataGridView隔行显示不同的颜色
    Oracle锁表了如何处理
    自1月4号起,不再在博客园更新笔记
    Spring 自定义注解+Aspect切面实现日志记录
    Spring @webFilter注解实现过滤器 省略配置xml
    druid配置随手记
  • 原文地址:https://www.cnblogs.com/weihanli/p/10057074.html
Copyright © 2011-2022 走看看