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

179
Vistas
Does the change of object in js is also local in a function?

The bellow generates a file containing code and prints the output of the program:

 class Code {
  static list = require("./settings.json");
  static fs = require("fs");
  constructor(
    code="print('Hello World')",//default code
    lang = "py",//language
    fn = "test",//file name
    args = "" //arguments
  ) {
    this.code = code;
    const path = require('path');
    this.fn = path.join(__dirname,fn) + "." + lang;//for platform independence
    this.run_com = Code.replace(Code.list[lang], this.fn, args);
    this._output="Server not responding";
              this._error="Server not responding";
  }

  file_exists()
  {
    return Code.fs.existsSync(`${this.fn}`);
  }

  make_file() {
    Code.fs.writeFile(`${this.fn}`, this.code, (err) => {
      if (err) {
        console.log(err);
      }
    });
  }

  run_file()
  {
      if(!this.file_exists())
      this.make_file();

      const { exec } = require("child_process");
      
      exec(this.run_com, (error, stdout, stderr) =>{
          if(error)
          {
              console.log(error);
          }
          
          else if(stderr==""){
          this._output=stdout;
          this._error="No error";
      }

          else{
          this._error=stderr;
          this._output=stdout;
          }
          console.log(this);//this
        });
        console.log(this);//this
  }

  get error()
  {
      return this._error;
  }

  get output()
  {
      return this._output;
  }

  static replace(
    s //replace {}
  ) {
    const arg = Object.values(arguments).slice(1); //convert obj to array removing s
    for (let i in arg) {
      s = s.replace("{}", arg[i]);
    }
    return s;
  }
}

a = new Code("print('exd')");
a.run_file();

In the above program the output is: enter image description here

The change in the state of object is not persistent once it comes out of the inner function.

why does the second console.log prints first and why the output of both the console.log are different, please justify in detail.

Also suggest a solution of this problem.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I think this is because exec is async and the second log is printed first. When the async code executes the second log is printed. And in the exec the values of _output and _error are changed hence the difference.

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