I'm trying to get some basic data from 2 different web api's (battery status and contacs) and write it into my .txt file
However when i do that, only one data gets written, as if it overwrites the other.
I know my code may look really bad, but im new to this and i really need help.
Code
//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);
});
Anyone kind enough to tell me what am i doing wrong?
According to the Node.js docs :
fs.writeFile(file, data[, options], callback)
Asynchronously writes data to a file, replacing the file if it already exists . data can be a string or a buffer.
So,what you're looking for is:
fs.appendFile(file, data[, options], callback)
Asynchronously append data to a file, creating the file if it does not yet exist. data can be a string or a buffer.
Hope this helps
Why don't you use fs.appendFile .
fs.appendFile('message.txt', 'data to append', function (err) {
});
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.