我如何访问跨Node.js输出的函数?

问题描述 投票:0回答:1

我有3个文件:

Ingredients.js

const fs = require("fs");
const readline = require('readline');
const stream = require('stream');


const ingredients = () => {
    const instream = fs.createReadStream('ingredients.txt');
    const outstream = new stream;
    const rl = readline.createInterface(instream, outstream);

    const listIngredients = {};


    rl.on('line', function (line) {
        let lower = line.toLowerCase();
        listIngredients[lower] = 0; 
    });

    rl.on('close', function () {
        console.log('listIngredients', listIngredients);
    });
}

module.exports = ingredients;

cookbook.js:

let fs = require("fs");

const book = () => {

    const regex = /\b(\w+)\b/g;

    fs.readFile('cook-book.txt', 'utf8', function (err, data) {

        let book = data;
        let lower = book.toLowerCase();
        let split = lower.match(regex);
        console.log(split);
    });

}
module.exports = book;

compare.js

const ingredients = require('./ingredients');
const book = require('./book');

每次尝试在食谱中提及成分时,我都试图提高其关键值。我认为应该将其放入另一个js文件中,以使其变得更干净。

虽然我可以从上述文件中console.log登出信息,但我无法弄清楚如何实际访问数据并更改compare.js中的Ingredients对象?

javascript arrays node.js object
1个回答
0
投票

正如其他人注意到的那样,您的ingredientsbook变量是在其作用域内具有必需信息而不在外部返回的信息的函数。要修复它,您必须返回值。

[当您使用异步内容时,您的函数应包装在Promise中以正确处理流程。

此代码应为您提供帮助:

const fs = require('fs');
const readline = require('readline');
const { Writable } = require('stream');
const fsp = fs.promises;

// ingredients.js
const getIngredients = async () => new Promise((resolve, reject) => {
  const instream = fs.createReadStream('ingredients.txt');
  const outstream = new Writable();
  const rl = readline.createInterface(instream, outstream);

  const listIngredients = {};

  rl.on('line', line => {
    const lower = line.toLowerCase();
    listIngredients[lower] = 0;
  });
  rl.on('error', reject);
  rl.on('close', () => resolve(listIngredients));
});

// cookbook.js
const getBookContent = async () => new Promise(async (resolve, reject) => {
  try {
    const wordRegEx = /\b(\w+)\b/g;
    const book = await fsp.readFile('cook-book.txt', 'utf8')
    const lower = book.toLowerCase();
    return resolve(lower.match(wordRegEx));
  } catch (error) {
    return reject(error);
  }
});

// compare.js
(async () => {
  const ingredients = await getIngredients();
  const words = await getBookContent();
  console.log(ingredients);
  console.log(words);
})();

为了更好地表示其实例,已对函数名称进行了更改。

我也使用了async iife来使用async/await语法,但是您仍然可以使用Promise本身

© www.soinside.com 2019 - 2024. All rights reserved.