readFileSync from an URL for Twitter media - node.js

僤鯓⒐⒋嵵緔 提交于 2019-12-02 04:06:56

The problem you have here is that trying you're using the 'File System (fs)' module to access a location not in your file system.

You would solve the getting of the image using the 'http' or 'https' modules. An example of usage would be:

const https = require('https');

function getImage(url, callback) {
    https.get(url, res => {
        // Initialise an array
        const bufs = [];

        // Add the data to the buffer collection
        res.on('data', function (chunk) {
            bufs.push(chunk)
        });

        // This signifies the end of a request
        res.on('end', function () {
            // We can join all of the 'chunks' of the image together
            const data = Buffer.concat(bufs);

            // Then we can call our callback.
            callback(null, data);
        });
    })
    // Inform the callback of the error.
    .on('error', callback);
}

// Then you 'get' your image like so:
getImage('https://www.example.com/image.png', function (err, data) {
    // Handle the error if there was an error getting the image.
    if (err) {
        throw new Error(err);
    }

    // Now you can use the rest of your code here:
    const client = new Twitter({ ... });
    // etc.
    // I've removed the rest because of size.
    return client.post(
        'media/upload',
        {media: data},
        function(error, media, response) {
            // ...
        }
    );
})

You cannot do http requests synchronously, and I strongly advise you try to avoid synchronous requests because of blocking (https://nodejs.org/en/docs/guides/blocking-vs-non-blocking/).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!