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!");});})()
6

Best Answer


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)})

thx for the diverse solutions. the simplest way for me was

node app.js > app.log 2>&1

This would redirect stdout to a file named app.log and redirect stderr to stdout.

So all my console.log are going to app.log

You can use JSON.stringify(obj), every object can be convert into string via this method.

I recommend not using console.log in production as it sync code.you can use winston instead

and you got in an easy way all the logs to file (if you wanted) by using new transports

const logger = winston.createLogger({level: 'info',format: winston.format.json(),defaultMeta: { service: 'user-service' },transports: [//// - Write to all logs with level `info` and below to `combined.log` // - Write all logs error (and below) to `error.log`.//new winston.transports.File({ filename: 'error.log', level: 'error' }),new winston.transports.File({ filename: 'combined.log' })]});

An addition to loicnestler's answer that means you don't need to change your 'console.log' statements:

Update the reference to 'console.log', so it calls 'writeFile' when logging:

const log = console.log;console.log = (data) => {log(data);<loicnestler's writeFile logic>}

In Node, console.log() calls util.inspect() to print objects.

You should call that directly and write it to a file.