如何在另外一个js文件中使用其他文件的变量或者函数,在客户端是不支持的

a.js

module.exports导出
Tips:一个文件只能有一个module.exports,想导出多个,就以对象的形式导出

  1. var a=10;
  2. module.exports=a;

module.exports对象形式

  1. var a=10;
  2. function show(){
  3. console.log("show");
  4. }
  5. module.exports={
  6. a,
  7. show
  8. }

exports导出

  1. var a=10;
  2. function show(){
  3. console.log("show");
  4. }
  5. exports.a=a;
  6. exports.show=show;(不推荐)

b.js

导入

  1. const a=require("./a");
  2. console.log(a);////{ a: 10, show: [Function: show] }

例子:抓取酷我搜索页
server2.js

  1. const puppeteer = require('puppeteer');
  2. const cheerio = require("cheerio");
  3. async function show(){
  4. const browser = await puppeteer.launch({
  5. headless: false,
  6. defaultViewport: null
  7. });
  8. /* 2.新建一个页面 */
  9. const page = await browser.newPage();
  10. /* 3.到达某个页面 */
  11. await page.goto('http://www.kuwo.cn/search/list?key=你');
  12. /* 4.在页面停顿5s */
  13. await page.waitForTimeout(5000)
  14. /* 5.获取页面中的内容 */
  15. var content = await page.content();
  16. var $ = cheerio.load(content, {
  17. decodeEntities: false
  18. })
  19. var item = $(".song_item");
  20. var arr = [];
  21. item.each((index, value) => {
  22. var title = $(value).find(".song_name a").html();
  23. var artist = $(value).find(".song_artist span").html();
  24. var imgUrl = $(value).find(".song_rank img").attr("src");
  25. arr.push({
  26. title,
  27. artist,
  28. imgUrl
  29. })
  30. })
  31. // console.log(arr);
  32. /* 6.关闭浏览器 */
  33. await browser.close();
  34. return arr;
  35. }
  36. module.exports = show;

index.js

  1. const koa = require("koa");
  2. const router = require("koa-router")();
  3. const app = new koa();
  4. /* 同级目录 ./ */
  5. const show = require("./server2.js");
  6. router.get("/",async ctx=>{
  7. let data = await show();
  8. ctx.body = data;
  9. })
  10. app.use(router.routes());
  11. app.listen(8000)