Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
Eval Javascript string and store stdout

I get Js as a string and I need to execute that script and compare the output to something. I'm using eval() here but can be anything. It runs on client side in the browser.

Is there any way to do this without changing the string a?

let a = "console.log(\"a\")";
eval(a);
let stdout = ???
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Using:

  • bind()
  • call()

you can extend console.log so that an additonal, separate live record is kept of all the log entries.

In the working example below, you can see that every time something is logged to the console, it is simultaneously added to the console.stdout array.


Working Example:

console.stdout = [];
console.logInclStdout = console.log.bind(console);

console.log = (logEntry) => {
    console.stdout.push(logEntry);
    console.logInclStdout.call(console, logEntry);
}


let a = "console.log('a')";
let b = "console.log('b')";
let c = "console.log('c')";

let saferFasterEval = (input) => Function(`"use strict"; ${input}`)();

saferFasterEval(a);
saferFasterEval(b);
saferFasterEval(c);

// When you want to see what has been logged via console.log
console.info(console.stdout);

about 4 years ago · Juan Pablo Isaza Report

0

If you want to save the messages executed with console.log inside the eval one way would be to overwrite the console.log however I would not recommend overwriting or using eval

// Store the original console.log function
const temp = console.log;

// Create an array to hold the commands
const cmds = []

// Overwrite the console.log to store the logs
console.log = (msg) => { cmds.push(msg) };

// Run A
let a = "console.log(\"a\")";
eval(a);

// Run B
let b = "console.log(\"b\")";
eval(b);

// Run C
let c = "console.log(\"c\")";
eval(c);

// Get the logs; You can use `cmd.join('\n')` to get the messages as a string
let stdout = cmds;

// Revert to orignal console.log
console.log = temp

Example: https://jsfiddle.net/x0w2q4Le/4/

about 4 years ago · Juan Pablo Isaza Report

0

Eval returns the output if you pass it to a variable:

let a = `
    let test = 10
    test++
    test
`
let stdout = eval(a)

Just put the value you want to return at the end

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!