【问题标题】:How to pass modules inputs while calling it from index.js file如何在从 index.js 文件调用模块时传递模块输入
【发布时间】:2018-07-01 02:00:44
【问题描述】:

我正在为使用专有 npm 模块在大型机模拟器上设置连接和执行操作(读取、写入和提交)的产品构建一些自定义插件。

我正在 index.js 文件中设置连接,并希望在调用时将终端变量传递给单独的模块

index.js sn-p

    var terminal;
    const mainframeTerminal =require(‘private_module’);
    const accountDetailsModule =require('./src/accountDetails');

    terminal = private_module.connect('11.11.11.1:789');
    let screen = await terminal.status();
    // expose module from index.js file so that it can be consumes in product
    export.getAccountDetails = accountDetailsModule.getAccountDetails(terminal) 

accountDetails.js

module.exports.getAccountDetails = async function(terminal){   
    //perform some operation with termianl var - passed from index file
    return data;
    }

我遇到以下错误 export.getAccountDetails = accountDetailsModule.getAccountDetails 不是函数。 我还需要传递数据输入,但暂时不需要, 如果我只需要传递任何输入,想知道 node.js 函数将如何理解映射。

请提供一些输入,我是编码新手。

【问题讨论】:

  • 我不知道,但也许export.getAccountDetails 应该是exports.getAccountDetails
  • 对不起,是拼写错误,它的出口

标签: javascript node.js node-modules


【解决方案1】:

喜欢这个

index.js

const mainframeTerminal =require('private_module');
const accountDetailsModule = require('./src/accountDetails');

const terminal = private_module.connect('11.11.11.1:789');
let screen = await terminal.status();

// expose module from index.js
exports = accountDetailsModule(terminal);

accountDetails.js

const getAccountDetails = async (terminal) => {
    // perform some operation
    return data;
}

exports = getAccountDetails;

CommonJS 中,模块只是分配变量的一种方式。因此,当您 require('./src/accountDetails') 时,您在 index.js 中得到的正是您在 accountDetails.js 中导出的(getAccountDetails 的值,这是一个带一个参数的异步函数)。

runMyCode.js

以下是您可以如何调用您的代码...

const mainframeTerminal =require('private_module');
const accountDetailsModule = require('./src/accountDetails');

const terminal = private_module.connect('11.11.11.1:789');
let screen = await terminal.status();

// run the code a print the result to console
accountDetailsModule(terminal).then(console.log);

【讨论】:

  • 你是如何调用你的代码的? index.js 是您要导入的模块,还是您的应用程序代码?如果是后者,您不需要或不需要 export 语句。见上面的runMyCode.js
猜你喜欢
  • 2023-01-30
  • 2018-09-26
  • 1970-01-01
  • 2021-04-20
  • 2019-11-19
  • 2019-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多