0

I have a program that returns the title of a youtube video when provided its id and it works fine. The issue is when I try to add the returned result to a text file it only adds the last string whereas when I console.log the result it prints the whole returned result. Where did I go wrong. How can I make it add the whole returned string into the text file. Any help is appreciated. Thanks in advance.

google.youtube('v3').videos.list({
  key: youtubeKey,
  part: 'snippet,contentDetails,statistics',
  id: 'Ks-_Mh1QhMc,c0KYU2j0TM4,eIho2S0ZahI',
}).then((response) => {
const {
  data
} = response;
data.items.forEach((item) => {
  const title = (`${item.snippet.title}`)
  console.log(title)//logs every result
  fs.writeFileSync('filePath', title)//logs only the last string
})
}).catch((err) => console.log(err));
});
anon20010813
  • 155
  • 7

1 Answers1

3

This is because you keep overwriting the file, so only the last string is in the file. You need to use appendFile, rather than writeFile, which overwrites the previous data.

 google.youtube('v3').videos.list({
  key: youtubeKey,
  part: 'snippet,contentDetails,statistics',
  id: 'Ks-_Mh1QhMc,c0KYU2j0TM4,eIho2S0ZahI',
}).then((response) => {
const {
  data
} = response;
data.items.forEach((item) => {
  const title = (`${item.snippet.title}`)
  fs.appendFileSync('filePath', title)//logs all strings
})
}).catch((err) => console.log(err));
});
R3FL3CT
  • 551
  • 3
  • 14