0

I am trying to write the global object to file from a node application.

As a starting point I know that writing Function('return this') in the console outputs the global object with all members.

So I am trying the following:

var fs = require("fs");
fs.writeFile("/Users/myuser/Desktop/log.txt", Function('return this')());

But it just writes [object global] to the file

  • Why is the output in the file different than the output in the console?
  • How can I output the entire global object to file?
3
  • JSON.stringify(Function('return this')) Commented Aug 24, 2017 at 9:03
  • Thank you for trying to help. I get "Uncaught exception: TypeError: Converting circular structure to JSON at JSON.stringify(<anonymous>)..." Commented Aug 24, 2017 at 9:13
  • If you're trying to JSON.stringify circular object, try this function stackoverflow.com/a/31557814/1951115 Commented Aug 24, 2017 at 9:17

1 Answer 1

2

You must pass a string to the body of the file you write to. Use

JSON.stringify(myObj)

Assuming Function return an object, you can do this:

var body = JSON.stringify( Function('return this')() );

fs.writeFile("/Users/myuser/Desktop/log.txt", body);

You should put a failsafe check also.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for trying to help. I get "Uncaught exception: TypeError: Converting circular structure to JSON at JSON.stringify(<anonymous>)..."
@user1283776, could you please put the full snippet? The output Function as well if short to include in the question.

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.