简体   繁体   中英

How do i write the contents of a variable into fs.writeFile

I'm fairly new to Node.js and coding in general but I'm trying to write the value of the variable named parsed into fs.writeFile()

Is there any way to do it because whenever I run this it creates the txt file but it has [object Object]

My apologies in advance if this doesn't make any sense:

https.get(`https://api.openweathermap.org/data/2.5/weather?zip=${zip},us&APPID=${config.key}`, res => {

    res.on('data', data => {
        body = data.toString();
    });

    res.on('end', () => {
        const parseData = JSON.parse(body);
        fs.writeFile('data.txt', parsedData)
        console.log(parsed_data);
    });

});

module.exports = wrappedAll;

[object Object] is the default conversion from an object to a string. Please be aware that in the following part of your code -

res.on('data', data => {
    body = data.toString();
});

You assign a different value to the body variable each time (overriding the previous value). What you want to do instead is to append to the body variable a new data chunk on every 'data' event.

It is crucial to understand that you don't get your data as a complete piece, you get it as a stream: on every 'on' event you get only part of it (and only on 'end' event you will have it as a whole) so it doesn't really make sense to parse it as a partially complete data piece.

You can parse your data when it finishes loading (on 'end' event), but, because you anyway write your response into a file, you can just leave your response as a string, you don't have or need to parse it anyway.

I suggest to do the following instead:

const https = require('https');
const fs = require('fs');

const url =
  "https://api.openweathermap.org/data/2.5/weather?zip=${zip},us&APPID=${config.key}";

function yourFunc(zip, config) {
  https.get(url, res => {
    let result = '';

    res.on('data', data => {
      result += data;
    });

    res.on('end', () => {
      fs.writeFile('data.text', result);
    });
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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