Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
How can I write the string output from a module to a file in a separate node.js file

I'm just starting to learn node.js (literally my second task) and I need to write two modules (one for prime numbers under 100 and one for even numbers under 50 - this is one separate requirement). The next requirement is that I import these modules to a node.js file and write the outcomes to 'nums.txt' file. If I write straight forward strings to files and run tests on them it executes perfectly, but when I try to write Array.toString() to the file I get

TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received type function ([Function (anonymous)])

What am I missing? I've read through most questions on here, gone through the documentation and tried everything from changing my module return statements and even trying to add toString in the filehandler.

These are the modules:

exports.primes = () => {
  const isPrime = () => {
    let sieve = [],
      i,
      j,
      n = 100,
      primeArr = [];

    for (i = 2; i < n; ++i) {
      if (!sieve[i]) {
        primeArr.push(i);
        for (j = i << 1; j <= n; j += i) {
          sieve[j] = true;
        }
      }
    }
    console.log(primeArr);
    return primeArr.toString();
  };
  isPrime();
};

exports.evenNums = () => {
  const isEven = () => {
    let n = 50;
    let evenArr = [];
    if (n === 1 || n === 0) {
      return false;
    }
    for (let i = 2; i <= n; ++i) {
      if (i % 2 === 0) {
        //console.log(i);
        evenArr.push(i);
      }
    }
    return evenArr.toString();
  };
  isEven();
};

My Node.js file

const primeN = require("./primes");
const evenN = require("./evenNums");
const fileHandler = require("fs");
const http = require("http");

const prime = primeN.primes();
const even = evenN.evenNums();
fileHandler.writeFile("nums.txt", prime, (err) => {
  if (err) {
    console.log("File not written\n");
  } else {
    console.log("File written successfully\n");
    console.log("The file has the following contents:");
    console.log(fileHandler.readFileSync("nums.txt"));
  }
  fileHandler.appendFile("nums.txt", even, (err) => {
    if (err) {
      console.log("File not written\n");
    } else {
      console.log("File written successfully\n");
      console.log("The file has the following contents:");
      console.log(fileHandler.readFileSync("nums.txt"));
    }
  });
});

http
  .createServer(function(req, res) {
    res.write("nums.txt");
    res.end();
  })
  .listen(8000);

I just know it is something simple that I'm missing but I can't seem to figure it out. Any tips on debugging Node.js would also be greatly appreciated.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There is a function inside of primes function. Even though isPrime is returning string but the primes function returns undefined.

exports.primes = () => {
  const isPrime = () => {
    let sieve = [],
      i,
      j,
      n = 100,
      primeArr = [];

    for (i = 2; i < n; ++i) {
      if (!sieve[i]) {
        primeArr.push(i);
        for (j = i << 1; j <= n; j += i) {
          sieve[j] = true;
        }
      }
    }
    console.log(primeArr);
    return primeArr.toString();
  };
  
  // return value from isPrime
  return isPrime();
};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda