Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write console.log to a file instead

Now I show the information using:

console.log (kraken.id, markets)

However, I want to write all the information that goes to the console to a file instead. How can that be done by completing the below code?

'use strict';
var ccxt = require('ccxt');

(async () => {
  let kraken = new ccxt.kraken()
  let markets = await kraken.load_markets()
  //console.log (kraken.id, markets)


  //How to write above console.log to file?
  const fs = require('fs');
  fs.writeFile("/Users/Andreas/Desktop/NODE/myproject/files/test.txt", "allinfoAsstring", function (err) {
    if (err) {
      return console.log(err);
    }

    console.log("The file was saved!");
  });
})()
like image 520
Andreas Avatar asked Feb 12 '19 16:02

Andreas


People also ask

How do you write the log data in the console to a file?

In Node, console. log() calls util. inspect() to print objects. You should call that directly and write it to a file.

What can I use instead of console log?

warn() Probably the most obvious direct replacement for log() , you can just use console. warn() in exactly the same way.

Can you console log in HTML file?

The console. log() method in HTML is used for writing a message in the console. It indicates an important message during testing of any program.


1 Answers

You can try to create an Object out of your variables and format them as a JSON string.

/* ... */
const obj = {kraken, markets}

const fs = require('fs');
fs.writeFile("/Users/Andreas/Desktop/NODE/myproject/files/test.txt", JSON.stringify(obj), function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("The file was saved!");
}); 

Later, you can retrieve the values from the file, by running

fs.readFile('/Users/Andreas/Desktop/NODE/myproject/files/test.txt', 'utf8', function(err, data) {
	const obj = JSON.parse(data)

	console.log("The data from the file is: " + obj)
})
like image 163
loicnestler Avatar answered Nov 15 '22 01:11

loicnestler