0

I have a JavaScript file (file.js) that contains the following code:

console.log("Hello World!")

When I run this code in my terminal node file.js, I get the following output:

Hello World

If I wanted to save this to a file programmatically (not right clicking and clicking save), does anyone know how I can do that?

The only solution I can find on the internet was using JSON.stringify("Hello World!"), but this doesn't do anything I don't believe (doesn't even output an error).

Reference: How to save the output of a console.log(object) to a file?

beeeZeee
  • 51
  • 1
  • 2
  • 10
  • 4
    If you mean from outside your program, you can just do `node file.js >output.txt`. If you mean from inside your program, look into some `fs` methods. – FZs Nov 24 '22 at 14:48
  • Does this answer your question? [Configure Node.js to log to a file instead of the console](https://stackoverflow.com/questions/8393636/configure-node-js-to-log-to-a-file-instead-of-the-console) – 0stone0 Nov 24 '22 at 14:58

2 Answers2

2

You'll need to overwrite console.log with your own implementation that writes the values it's called with to a file.

const { appendFileSync } = require('fs');
const origConsole = globalThis.console;
const console = {
    log: (...args) => {
        appendFileSync('./logresults.txt', args.join('\n') + '\n');
        return origConsole.log.apply(origConsole, args);
    }
}

console.log("Hello World!");
console.log("another line", "yet another line");

If you called this frequently enough such that the sync writes are a problem, you could use appendFile or fs.promises.appendFile so that the writes don't block and use a queue for the pending values to write.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

I suppose that your console.log() is some kind of text output you get from somewhere, so i made a randomstring gen function just to exemplify.

You just need to use the fs module from Node, then write the file to your system.

Like this:

const fs = require('fs');

const randomString = () => {
  return Math.random().toString(36).substring(7);
};


const createFile = (fileName, content) => {
    fs.writeFile(fileName, content, (err) => {
        if (err) throw err;
        console.log('The file has been saved!');
    });
}

createFile('test.txt', randomString());

Just note that if you're receiving text from an iteration, you maybe wanna insert '\n' on the end of each iteration to break the line on your text file.