10

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!");
  });
})()
xxx
  • 1,153
  • 1
  • 11
  • 23
Andreas
  • 1,121
  • 4
  • 17
  • 34
  • 2
    easiest solution would be running it, so it would pipe to the file `node yourscript.js > file.log 2>&1` – Flash Thunder Feb 12 '19 at 16:50
  • 3
    Possible duplicate of [Node: log in a file instead of the console](https://stackoverflow.com/questions/8393636/node-log-in-a-file-instead-of-the-console) – Arman P. Feb 12 '19 at 16:52

6 Answers6

22

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)
})
loicnestler
  • 517
  • 3
  • 8
11

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

0

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

Guseyn Ismayylov
  • 367
  • 5
  • 16
0

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' })
  ]
});
Shay Moshe
  • 482
  • 4
  • 16
  • What did you mean "as it sync code"? That console.log is blocking whereas winston logger is not? – samlaf Mar 05 '22 at 19:11
  • 2
    @samlaf yes, exactly! `console.log` blocks the main thread while running (for example when printing out huge objects) while (apparently) winston does not. – loicnestler Oct 27 '22 at 09:07
0

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>
}
Scott Wager
  • 758
  • 11
  • 9
-1

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

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

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • I am a bit new to node.js so I am not sure how to do this exactly. Is it possible to show some code how I can do that with reference to my code snippet to have a good example? – Andreas Feb 12 '19 at 16:59
  • What don't you understand? Are you asking how to call a function? How to write to a file? Did you read the documentation? – SLaks Feb 12 '19 at 17:20