【问题标题】:calling nodejs module1.js from module2.js then parse some variables从 module2.js 调用 nodejs module1.js 然后解析一些变量
【发布时间】:2020-05-17 18:17:40
【问题描述】:

又是我。 :-D 我的下一个奇怪的问题是:

我有 2 个 nodejs 模块:

//module1.js

const prompt = require('prompt');
var Excel = require('exceljs');


var wbCO = new Excel.Workbook();
var iCO = 1;
wbCO.xlsx.readFile('costumers.xlsx').then(function (){
  shCO = wbCO.getWorksheet("Sheet");
  while (iCO <= shCO.rowCount){  
    console.log(shCO.getRow(iCO).getCell(1).value +" - "+ shCO.getRow(iCO).getCell(2).value);
    iCO++;
  }

});

prompt.start();

prompt.get([{name:'costumer', required: true, conform: function (value) {
  return true;
}
}], function (key_err, key_result) {
    if (key_err) { return onErr(key_err); }

    var Ccostumer = shCO.getRow(key_result.costumer).getCell(2).value;
    var user = shCO.getRow(key_result.costumer).getCell(3).value;
    var pass = shCO.getRow(key_result.costumer).getCell(4).value;

    function onErr(key_err) {
      console.log(key_err);
      return 1;
    }  

});

       //module2.js

wb.xlsx.readFile('./'+Ccostumer+'/File.xlsx').then(function(){

sh = wb.getWorksheet("Sheet1");

    start_page(sh);
});

async function start_page(sh){  
  var i = 2;
  var result_id = 1;

    const browser = await puppeteer.launch({headless: true});

    while(i <= sh.rowCount){
    var result_cell = sh.getRow(i).getCell(3).text;
        await open_page(browser, result_cell, result_id);
        i++;
        result_id++;
  }
  browser.close();

}

        async function open_page(browser, result_cell, result_id) {

            const page = await browser.newPage();   
            page.setDefaultNavigationTimeout(100000);       

            await page.goto('https://www.mywebsite.com', {
                waitUntil: 'networkidle2'
            });
                //  authentication
                await page.waitFor('input[name="ctl00$ContentPlaceHolder1$Signin1$txtEmail"]');
                await page.$eval('input[name="ctl00$ContentPlaceHolder1$Signin1$txtEmail"]', elu => elu.value = user);
                await page.waitFor('input[name="ctl00$ContentPlaceHolder1$Signin1$txtPassword"]');
                await page.$eval('input[name="ctl00$ContentPlaceHolder1$Signin1$txtPassword"]', elp => elp.value = pass);
                await page.click('input[type="submit"]');
                await page.waitForNavigation();

                //search
                await page.waitFor('input[name="email"]');
                    await page.type('input[name="email"]', result_cell);
                await page.click('input[type="submit"]');

我正在尝试通过 const md1 = require('./module1.js'); 从 module2.js 调用 module1.js 但我没有得到变量,并且两者都在同时运行。

这是我的问题:

1 - 如何在我在 module1.js 做出选择后运行 module2.js,然后按 ENTER。

2 - 如何将这些变量从 module1.js 解析到 module2.js(Ccostumer、user、pass)。

【问题讨论】:

    标签: javascript node.js variables node-modules prompt


    【解决方案1】:

    在nodejs中,每个文件都有自己的作用域,每个文件中声明的变量和函数都属于它们。

    为了让您能够从另一个 .js 文件访问函数或变量,您需要显式导出它们

    file1.js

    console.log('loading file 1') // runs when the file is loaded
    
    function fileOneFunc () {
      // next line runs only when the function is called
      console.log('this is the fileOneFunc running')
    }
    
    module.exports = fileOneFunc
    

    file2.js

    // the following line will have access to the exported function from file1
    const f1 = require('./file1')
    
    console.log(typeof f1)
    
    f1()
    

    因此,如果您希望 module1.js 中的代码仅在您希望来自 module2.js 内的调用时运行,您必须将 module1.js 中的代码包装在一个函数中,然后如上所示将其导出。

    然后在你的module2.js 中你说你想做的事

    const md1 = require('./module1.js')
    

    然后,只要您认为合适,就调用md1 函数。

    【讨论】:

      【解决方案2】:

      如果你想从一个模块中返回一些东西,你只需要返回一些东西。如果您 require 另一个 Node JS 脚本,它不会自动返回任何内容,它主要只是“运行”脚本。

      使用 module.exports

      这里是 2 个模块的基本示例,一个被另一个调用并返回一个值。在此示例中,模块 1 正在导出一个函数,然后需要该函数并在模块 2 中调用该函数。

      // module1.js 
      module.exports = () => {
      
         /* doing stuff here */
      
         return "someValue";
      
      });
      
      // module2.js
      
      const value = require('./module1')();
      console.log(value);
      
      >> "someValue"
      

      您必须稍微重新排序您的逻辑,并可能在函数周围包装一些东西。您希望在您在模块 1 中做出选择后运行模块 2。意味着,您想从 module1 调用 module2。也意味着您需要在 module1 中使用 module2,并且在您做出选择后,您需要使用输出运行 module2。理论上这看起来像这样:

      你的例子

      虽然我不相信你的代码示例是完整的,但我会尽力给你一个提示。但我不会为你做这项工作

      // module1.js
      
      const prompt = require('prompt');
      const Excel  = require('exceljs');
      const module2 = require('./module2');
      
      const workbook = new Excel.Workbook();
      let counter = 1;
      
      workbook.xlsx.readFile('costumers.xlsx').then( function () {
      
        // Get Worksheet from Workbook
        const sheet = workbook.getWorksheet("Sheet");
      
        // Print Values of Worksheet
        while (counter <= sheet.rowCount) {
          const value1 = sheet.getRow(counter).getCell(1).value;
          const value2 = sheet.getRow(counter).getCell(2).value;
          console.log(`${value1} - ${value2}`);
          counter++;
        }
      
        // Open prompt
        prompt.start();
      
        // Get result from prompt
        prompt.get([
          {
            name:'costumer',
            required: true
          }
        ], function (key_err, key_result) {
      
          if (key_err) { return console.log(key_err); }
      
          const costumer = sheet.getRow(key_result.costumer).getCell(2).value;
          const user = sheet.getRow(key_result.costumer).getCell(3).value;
          const  pass = sheet.getRow(key_result.costumer).getCell(4).value;
      
          return module2(costumer, user, pass);
      
        });
      
      });
      
      // module2.js
      
      module.exports = function (costumer, user, pass) {
      
        // Do something with costumer, user, pass
        // the value you get in return from the prompt in module1.js
      
      }
      

      确保你的module1.js 和module2.js 在同一个目录下,否则require('./module2') 不起作用

      【讨论】:

      • 谢谢@Pascal 我得到了 TypeError: module2 is not a function。你能把我的代码放进去看看更好吗?
      • @KonradSoares 我稍微更新了我的答案以适合您的代码。提示:对变量使用更清晰的命名。如果你让它工作,请告诉我。另外,如果答案对您有帮助:请标记为正确。
      • 非常感谢@Pascal。它正在工作,但我遇到了一些问题 (node:21244) UnhandledPromiseRejectionWarning: E​​rror: Evaluation failed: ReferenceError: user is not defined at puppeteer_evaluation_script :1:21。使用 page.type 它正在工作,但在下一个输入中,我需要重写用户并通过。如何选择输入文本中的文本然后重写凭据?
      • 现在好了。我已经使用了三下单击来选择文本,然后再次键入。等待 page.click('input[name="ctl00$ContentPlaceHolder1$Signin1$txtEmail"]', {clickCount:3});再次感谢您。
      • 很高兴我能帮上忙!一旦您了解了 Nodejs 的整个“模块”工作流程,一切都会变得轻而易举!
      猜你喜欢
      • 2020-02-09
      • 2015-02-20
      • 2020-04-29
      • 2021-02-13
      • 2021-02-01
      • 2015-04-27
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      相关资源
      最近更新 更多