简体   繁体   English

将console.log()内容管道传输到Node.js中的.txt文件

[英]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. 我有一个Node.js文件,可以将一堆测试结果(轻松地> 1000行)输出到终端。 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. console.log()仅存在于此,因为我找不到其他方法来查看结果。 I need a way to create a file through Node.js, not the command line, that contains all of the CLI output/results. 我需要一种通过Node.js(而不是命令行)创建包含所有CLI输出/结果的文件的方法。

I thought that fs.appendFile('example.txt', 'append this text to the file', (err) => {}); 我以为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 . 可能有用,但是我需要“附加”到文件的是函数的results When I try that, the file only contains [object Object] instead of the actual results of the tests. 当我尝试这样做时,该文件仅包含[object Object],而不包含测试的实际结果。

I'm a beginner to Node, any advice is highly appreciated. 我是Node的初学者,任何建议都非常感谢。

You are close, but you need to include the appendFile inside of your other function. 您已经很接近了,但是您需要在其他函数中包括appendFile。 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 如果将output: json添加到flags对象,则可以使用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');
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM