-2

I have a code saved in string. For eg:
const code = "res.send("Hi")";
How can I execute the above code in JS? I wanna execute the code of the code variable.
I can't just write code;. The code doesn't execute. Please Help.

FatFatty
  • 76
  • 1
  • 13
  • 6
    [`eval(code)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) - but be careful, that is risky. – luk2302 Jun 19 '22 at 18:07
  • 1
    Sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Why do you need this? What is the context? – Ivar Jun 19 '22 at 18:08
  • I need it to send message to multiple sockets – FatFatty Jun 19 '22 at 18:16
  • Why does that require you to have it in a string? Why not just call `res.send("Hi")`? Or put it in a function and call that function? – Ivar Jun 19 '22 at 18:17
  • I'm looping `.to()` multiple times `socket.to("fi_GtczEsa1_tjBjAAAD").to("e07k37w3p880SJXDAAAH").emit("notifications", {notifications: [...newUser.notifications],})` to send the notifications to all the connected devices of the user. – FatFatty Jun 19 '22 at 18:18
  • 2
    [Then use a loop to chain the `.to()`](https://jsfiddle.net/r8a4smvh/) so you don't have to use a string. Having it in a string is not the way to go here. – Ivar Jun 19 '22 at 18:28
  • 1
    @Ivar Thats a good way to do it. I'll use it instead of combining in string. – FatFatty Jun 19 '22 at 18:35

1 Answers1

2

use eval

const code = "console.log('Hi')";

eval(code)
kerm
  • 653
  • 1
  • 5
  • 15