当前位置: 移动技术网 > IT编程>开发语言>JavaScript > nodejs 使用 js 模块的方法实例详解

nodejs 使用 js 模块的方法实例详解

2018年12月05日  | 移动技术网IT编程  | 我要评论
intro# 最近需要用 nodejs 做一个爬虫,google 有一个 puppeteer 的项目,可以用它来做爬虫,有关 puppeteer 的介绍网上也有很多,在这

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

总结

以上所述是小编给大家介绍的nodejs 使用 js 模块的方法实例详解,希望对大家有所帮助

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网