Reputation: 370
I have two functions,
1) download(uri, filename, callback)
-> Downloads an image to a specific location
2) twitterPost(filename)
-> Tweets the image
I need to do this Asynchronously - so I call twitterPost
after the image is done downloading, however I receive this error every time:
throw new Error('File path does not exist: ' + media);
^
Error: File path does not exist: Imgs/18478-wrt1114.jpg
Now I understand that this is appearing because the image has not downloaded, however it doesn't make sense seeing that the callback function is called after the pipe is closed. Here is my code for both functions:
function download(uri, filename, callback) {
request.head(uri, function(err, res, body) {
request(uri).pipe(fs.createWriteStream(filename)).on('end', callback);
});
};
and
function twitterPost(filename) {
var twitterRestClient = new Twitter.RestClient(
// API KEYS AND STUFF HERE
);
twitterRestClient.statusesUpdateWithMedia(
{
'status': 'Test Tweet',
'media[]': filename
},
function(error, result) {
if (error) { console.log('Error: ' + error.message) }
if (result) { console.log(result.text) }
});
}
Here is my function call:
download(image, filename,twitterPost(filename));
Am I using callbacks incorrectly, or is there some other issue that I am not noticing causing this problem
Thank you for you help!
Upvotes: 1
Views: 112
Reputation: 665555
Am I using callbacks incorrectly
Yes, you're not actually passing a callback function. You pass the result of immediately invoking twitterPost(filename)
- which happens even before download
is invoked, so there is no such file yet.
Use a function expression around this call, to get that function called by download
:
download(image, filename, function(endEvent) {
twitterPost(filename);
});
Upvotes: 2
Reputation: 562
I think your problem is due to the way you pass arguments to your function.
download(image, filename,twitterPost(filename));
check in twitterPost(filename)
that your filename is as expected. I'm pretty sure it wont. That's because your twitterPost function is not called with this argument. It is called with :
request(uri).pipe(fs.createWriteStream(filename)).on('end', callback);
that is, no arguments. I'd do :
request(uri).pipe(fs.createWriteStream(filename)).on('end', function(){
callback(filename);
});
Upvotes: -1