将网页数据写入 TXT 文件

Writing web data to a TXT file

(我想使用节点获取而不是请求)

我想将网页 (E.X google.com) 中的数据写入 TXT 文件 (E.X google.txt),但无法正常工作。当我 运行 脚本然后检查我的 "google.txt" 文件时,它说的是 [object Object].

这是我的代码:

const fs = require('fs');


request('https://google.com', function (error, body) {

    fs.writeFile('google.txt', body, (err) => {
        if (err) throw err;

        console.log('Wrote google.com to google.txt !');
    });

});

你所谓的body并不是真正的HTTP响应体,而是响应对象。重命名使其清晰,然后使用 .body 属性:

request('https://google.com', function (error, res) {

    fs.writeFile('google.txt', res.body, (err) => {
        if (err) throw err;

        console.log('Wrote google.com to google.txt !');
    });

});