1

Is there a way to execute a JavaScript string as some functions? I'm using eval but it isn't working.

I'm trying this as I need to read values from a YML file for my serenity js test.

This is what I'm trying to do

this.data = "element1.element2" 
this.test1 = "safeLoad(readFileSync(`config/${this.fileName}.yml`, 'utf8'))";
console.log(this.test1)
console.log(`${this.test1}.${this.data}`);

And this is how I'm trying to execute the string

eval(`${this.testabc}.${this.data}`)

However, when I execute this, I'm having the following error:

ReferenceError: safeLoad is not defined

P.S.: If I execute the code normally (without eval) it works fine!

safeLoad(readFileSync(`config/${this.fileName}.yml`, 'utf8')).element1.element2

Does anyone know how to execute code like that as a string?

2
  • It's a scoping issue. You should probably check How does the “this” keyword work? and JavaScript Scope. Since it's impossible to know what this actually stands for within your question, all I can say with certainty is that it's looking for the safeLoad function in the wrong scope. Commented Dec 29, 2019 at 13:53
  • There are lots of reasons why not to do this (security), however I suspect safeLoad is out of scope for eval, check stackoverflow.com/questions/9781285/… Commented Dec 29, 2019 at 13:56

1 Answer 1

0

I guess you import safeLoad using es6 syntax.

If yes, when you use babel to transpile code, safeLoad will be omitted. Because the transpiler though that safeLoad will not be used on your code.

To understand, please check the bellowing picture, or this babel example.

enter image description here

To fix this, you should use require instead of import(es6):

// instead of
import safeLoad from 'safeLoad'
// use this:
const safeLoad = require('safeLoad').default

// instead of
import { safeLoad } from 'safeLoad'
// use this:
const { safeLoad } = require('safeLoad')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.