【问题标题】:How to write GET api into existing files in node.js如何将 GET api 写入 node.js 中的现有文件
【发布时间】:2016-07-02 06:50:40
【问题描述】:

我正在尝试从 2 个不同的 web api(电池状态和联系人)获取一些基本数据并将其写入我的 .txt 文件中

但是,当我这样做时,只会写入一个数据,就好像它会覆盖另一个数据一样。

我知道我的代码可能看起来很糟糕,但我是新手,我真的需要帮助。

代码

//GET - Battery status
var options = {
    host: 'www.w3.org',
    port: 80,
    path: '/work'
};

http.get(options, function (response) {
    console.log("Response: " + response.statusCode);
    console.log("Header:" + JSON.stringify(response.headers));
    fs.writeFile("external-api.txt", "Responsecode:" + response.statusCode + "\nHeaders:" + JSON.stringify(response.headers))       
}).on('error', function (e) {
    console.log("Napaka!: " + e.message);
});

//GET ZAHTEVE - Contacts
var options = {
    host: 'www.google.com',
    port: 80,
    path: '/work'
};

http.get(options, function (response) {
    console.log("Odgovor: " + response.statusCode);
    console.log("Header:" + JSON.stringify(response.headers));
    fs.writeFile("external-api.txt", "Responsecode:" + response.statusCode + "\nHeaders:" + JSON.stringify(response.headers))
}).on('error', function (e) {
    console.log("Napaka!: " + e.message);
});

结果

谁能告诉我我做错了什么?

【问题讨论】:

    标签: javascript node.js api http get


    【解决方案1】:

    根据Node.js docs

    fs.writeFile(file, data[, options], callback)

    将数据异步写入文件,如果文件已存在则替换文件。数据可以是字符串或缓冲区。

    所以,你要找的是:

    fs.appendFile(file, data[, options], callback)

    异步追加数据到文件,如果没有则创建文件 还存在。数据可以是字符串或缓冲区。

    希望对你有帮助

    【讨论】:

    • 谢谢谢谢,非常感谢!完美运行:)
    【解决方案2】:

    你为什么不使用 fs.appendFile 。

     fs.appendFile('message.txt', 'data to append', function (err) {
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2018-09-23
      • 2019-03-05
      相关资源
      最近更新 更多