Home > Blockchain >  Node.js Exported Array isn't filled
Node.js Exported Array isn't filled

Time:08-19

i want to export an Array. The Array is in my

Fact.js

var facts = [];

exports.facts = facts;

function init() {
    loadFacts();
}

exports.init = init;

function loadFacts() {
    if (facts.length === 0) {
        facts = [];
        SelectAll(function (messages) {
            facts = messages;
            console.log("loadFacts: "   JSON.stringify(facts));
        });
    }
}

async function SelectAll(callback) {
    myJsonArray = [{ info: "a", source: "b" }, { info: "c", source: "d" }];
    test = JSON.parse(JSON.stringify(myJsonArray))
    console.log("SelectAll: "   JSON.stringify(test));
    return callback(test);
}

In my server.js I call the init-Function to load my facts.

server.js

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const Fact = require('./Fact');

const app = express();

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));


Fact.init();

console.log("Server.js: "   JSON.stringify(Fact.facts));

In the server.js the Array Fact.facts is empty after calling the Function init().

enter image description here

Does anybody knows why this happens?

Thanks in Advance

CodePudding user response:

That is because you exported the initial facts array (which was empty), and then reassigned new array [] to facts variable. Exported array-object is not affected with your code. So instead of reassignment you need to modify your exported array object.

Changes:

const facts = []; // const just to ensure the reference to array is not overwritten

function init() {
  loadFacts();
}

function loadFacts() {
  if (facts.length === 0) {
    SelectAll(function (messages) {
      facts.push(...messages); // push instead of reassignment
      console.log("loadFacts: "   JSON.stringify(facts));
    });
  }
}

async function SelectAll(callback) {
  const myJsonArray = [
    { info: "a", source: "b" },
    { info: "c", source: "d" }
  ];
  const test = JSON.parse(JSON.stringify(myJsonArray));
  console.log("SelectAll: "   JSON.stringify(test));
  return callback(test);
}

module.exports = {
  facts: facts,
  init: init
};

Output will be:

SelectAll: [{"info":"a","source":"b"},{"info":"c","source":"d"}]
loadFacts: [{"info":"a","source":"b"},{"info":"c","source":"d"}]
Server.js: [{"info":"a","source":"b"},{"info":"c","source":"d"}]
  • Related