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?
user1283776
  • 19,640
  • 49
  • 136
  • 276

1 Answers1

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.

Adam Azad
  • 11,171
  • 5
  • 29
  • 70
  • Thank you for trying to help. I get "Uncaught exception: TypeError: Converting circular structure to JSON at JSON.stringify()..." – user1283776 Aug 24 '17 at 09:06
  • @user1283776, could you please put the full snippet? The output `Function` as well if short to include in the question. – Adam Azad Aug 24 '17 at 09:07