Search code examples
javascriptnode.jsconsole.loglighthouse

Piping console.log() contents to a .txt file in Node.js


I have a Node.js file that outputs a bunch of test results, easily >1000 lines, to Terminal. The file looks something like this:

launchChromeAndRunLighthouse('https://www.apple.com/', flags).then(results => { console.log(results); });

The console.log() is only there because I couldn't figure out another way to view the results. I need a way to create a file through Node.js, not the command line, that contains all of the CLI output/results.

I thought that fs.appendFile('example.txt', 'append this text to the file', (err) => {}); could be of use, but what I need to "append" to the file is the function's results. When I try that, the file only contains [object Object] instead of the actual results of the tests.

I'm a beginner to Node, any advice is highly appreciated.


Solution

  • You are close, but you need to include the appendFile inside of your other function. This assumes that your 'results' object is of the string type. If not then you need to get the string version of this object.

    The lighthouse docs specify the format of the log information that is returned. If you add output: json to the flags object then you can use it lik

    launchChromeAndRunLighthouse('https://www.apple.com/', flags).then(results => { 
        fs.appendFile('example.txt', JSON.stringify(results), (err) => {
            console.log('error appending to file example.txt');
        });
    });