0

So I am making a twitter bot using Node.js and the Twit library,so to send pictures along with your tweets you need to upload a image to twitter and get a media-id-string which relates to your image. So in my code i couldn't really get the media id without well sighs writing the string to a txt file and outside the function returning it, yes i know it very very janky. Also the function 1 is running after function 2, i think its running asyncronosly but I'm not sure. So can anyone help me fix this bad code

This is my code:

function upload_media(){
  var b64content = fs.readFileSync('download.jpg').toString('base64')
  T.post('media/upload', { media_data: b64content }, function (err, data, response){ //Function 1
    fs.writeFileSync('media-string.txt', data.media_id_string)
  })
  media_string =  fs.readFileSync('media-string.txt', {encoding:'utf8'})//Function 2
  return media_string
}
OpenSaned
  • 105
  • 1
  • 1
  • 8
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – VLAZ Aug 16 '21 at 09:33

1 Answers1

0

use async await syntax use fs.readfile and fs write file instead of fs.readfileSync

something like this How to read file with async/await properly?

const uploadmedia = async () => {
  var b64content = await fs.readFile('follow example');
};
majid
  • 404
  • 4
  • 8