Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

186
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda