How to use follow-redirects - 10 common examples

To help you get started, we’ve selected a few follow-redirects examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github CodeDotJS / instavim / cli.js View on Github external
// because initiall imageHD shows output in array ['150', '150'] and null
				console.log(colors.cyan.bold('\n ❱ Image Resolution      :    ✔\n'));

				// if case is null
			} else if (notHDArray[0] === imageHD[0]) {
				console.log(colors.red.bold('\n ❱ Image Resolution      :    ✖\n'));
			}

			// using previously made function
			const remChars = parsedImages(imageLink);

			// saving image
			const imageFile = fs.createWriteStream(removeSlash + argv.n + '.jpg');

			// downloading image
			https.get(remChars, res => {
				res.pipe(imageFile);

				console.log(colors.cyan.bold(' ❱ Image Saved In        : '), ' ', colors.green.bold(savedIn), colors.cyan.bold('❱'), colors.green.bold(argv.n + '.jpg\n'));
			}).on('error', err => {
				console.log(err);

				console.log('❱ Failed to Save the image');

				process.exit(1);
			});
		}
	});
});
github CodeDotJS / instavim / cli.js View on Github external
}
	});
}

// checking internet connection
checkInternet(isConnected => {
	if (isConnected) {
		console.log(colors.cyan.bold('\n ❱ Internet Connection   :    ✔\n'));
	} else {
		// stop the whole process if the network is unreachable
		console.log(colors.red.bold('\n ❱ Internet Connection   :    ✖\n'));
		process.exit(1);
	}
});

const req = https.request(options, res => {
	if (res.statusCode === 200) {
		console.log(colors.cyan.bold(' ❱ Valid Username        :    ✔'));

		setTimeout(() => {
			mkdirp(removeSlash, err => {
				if (err) {
					// optional
					console.log(colors.red.bold(boxen('Sorry! Couldn\'t create the desired directory')));
				} else {
					/* do nothing */
				}
			});
		}, 1500);
	} else {
		// stopping the whole process if the username is invalid
		console.log(colors.red.bold(' ❱ Valid Username        :    ✖\n'));
github pietercolpaert / ldfetch / lib / NodeHttpFetcher.js View on Github external
//extracted chunks to be added to the array
        responseStream.on('data', function (chunk) {
          chunks.push(chunk);
        });
        res.on('error', function (error) {
          onResponse(error);
        });
        responseStream.on('end', function () {
          self.emit('downloaded', { url: url, totalBytes: totalBytes });
          onResponse(null, res, chunks.join(''));
        })
      };
    if (parsedUrl.protocol === 'https:') {
      activeRequest = https.request(settings, executionResponse);
    } else if (parsedUrl.protocol === 'http:') {
      activeRequest = http.request(settings, executionResponse);
    } else {
      console.error('WARNING: Only http or https supported. Not ' + parsedUrl.protocol);
      deferred.reject(url + ' not using a protocol we can handle');
    }
    if (activeRequest) {
      activeRequest.on('error', function (e) {
        deferred.reject(e.message);
      });
      activeRequest.end();
      // Mark the request as active
      self._active[requestId] = { request: activeRequest, result: deferred.promise };
      self._pending++;
    }
  }
github pietercolpaert / ldfetch / lib / NodeHttpFetcher.js View on Github external
totalBytes += chunk.length;
        });
        //extracted chunks to be added to the array
        responseStream.on('data', function (chunk) {
          chunks.push(chunk);
        });
        res.on('error', function (error) {
          onResponse(error);
        });
        responseStream.on('end', function () {
          self.emit('downloaded', { url: url, totalBytes: totalBytes });
          onResponse(null, res, chunks.join(''));
        })
      };
    if (parsedUrl.protocol === 'https:') {
      activeRequest = https.request(settings, executionResponse);
    } else if (parsedUrl.protocol === 'http:') {
      activeRequest = http.request(settings, executionResponse);
    } else {
      console.error('WARNING: Only http or https supported. Not ' + parsedUrl.protocol);
      deferred.reject(url + ' not using a protocol we can handle');
    }
    if (activeRequest) {
      activeRequest.on('error', function (e) {
        deferred.reject(e.message);
      });
      activeRequest.end();
      // Mark the request as active
      self._active[requestId] = { request: activeRequest, result: deferred.promise };
      self._pending++;
    }
  }
github cosmo0 / arcade-manager / src / updater.js View on Github external
checkUpdate() {
        // get all tags from repository
        let url = '/repos/cosmo0/arcade-manager/tags';
        https.get({ protocol, 'host': api, 'path': url, 'headers': { 'User-Agent': 'arcade-manager' } }, (res) => {
            res.setEncoding('utf8');
            let rawData = '';
            res.on('data', (chunk) => { rawData += chunk; });
            res.on('end', () => {
                // parse version number
                let data = JSON.parse(rawData);
                let latest = data[0].name.replace('v', '');
                console.log('latest version: %s', latest);

                // version has been ignored
                if (settings.has('ignoreVersion') && settings.get('ignoreVersion') === latest) {
                    console.log('Version has been ignored: %s', latest);
                    return;
                }

                // if a newer version is available, ask user to download it
github cosmo0 / arcade-manager / src / downloader.js View on Github external
res.on('end', () => {
                let siblingFolders = JSON.parse(rawDataFolders);
                for (let f of siblingFolders) {
                    if (f.path === folder) {
                        // get full list of files from this folder
                        let urlFullFilesList = '/repos/' + repository + '/git/trees/' + f.sha;
                        console.log('Listing files for tree %s', f.sha);
                        https.get({ protocol, 'host': api, 'path': urlFullFilesList, 'headers': { 'User-Agent': 'arcade-manager' } }, (res) => {
                            res.setEncoding('utf8');
                            let rawDataFiles = '';
                            res.on('data', (chunk) => { rawDataFiles += chunk; });
                            res.on('end', () => {
                                callback(JSON.parse(rawDataFiles).tree);
                            });
                        });
                        break;
                    }
                }
            });
        });
github jhekasoft / insteadman2 / src / lib / manager.js View on Github external
installGame(game, downloadStatusCallback, beginInstallationCallback, endInstallationCallback) {
        var tempGamePath = this.configurator.getTempGamePath();
        this.configurator.checkAndCreateDirectory(tempGamePath);
        var tempPartGameFilepath = tempGamePath + 'tmp_' + game.name + '.part';
        var tempGameFilepath = tempGamePath + path.basename(game.url);

        var url = game.url;
        var bar;
        var file = fs.createWriteStream(tempPartGameFilepath);
        var here = this;
        http.get(url, function (res) {
            console.log(res);
            var total = res.headers['content-length'] || 0;
            console.log('total: ' + total);
            // TODO: try res.headers['content-disposition'] for filename
            // tempGameFilepath = ;
            bar = statusBar.create({total: total})
                .on('render', function (stats) {
                    downloadStatusCallback(game, {
                        percents: stats.percentage,
                        totalSize: stats.totalSize,
                        currentSize: stats.currentSize,
                        speed: stats.speed
                    });
                });

            res.pipe(file);
github neo4j-graphql / neo4j-graphql-cli / src / index.js View on Github external
} catch (e) {
      console.log(chalk.red.bold("Unable to read " + schemaFilename + " - falling back to default movieSchema.graphlql"));
      schema = config.DEFAULT_SCHEMA;
    }
  }

  var options = {
    headers: {
      'Authorization': "Basic " + new Buffer("neo4j:" + creds.password).toString('base64')
    },
    host: helpers.constructProxyIp(creds),
    path: '/graphql/idl',
    method: 'POST'
  }

  var req = https.request(options, (res) => {

    res.on('data', (chunk) => {
      // got some data
    });
    
    res.on('end', (d) => {
      //process.stdout.write(d);

      if (res.statusCode == 200) {
        return callback(null, creds)
      } else {
        return callback("Error, posting the schema IDL failed. Please ensure your schema format is valid.");
      }
      
    });
github jakemmarsh / node-soundcloud / lib / soundcloud.js View on Github external
hostname: data.uri,
      path: data.path + paramChar + qsdata,
      method: data.method
    };
    var req;
    var body;

    if ( data.method === 'POST' ) {
      options.path = data.path;
      options.headers = {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Content-Length': qsdata.length
      };
    }

    req = https.request(options, function (response) {
      body = '';
      response.on('data', function (chunk) {
        body += chunk;
      });
      response.on('end', function () {
        try {
          var d = JSON.parse(body);
          // See http://developers.soundcloud.com/docs/api/guide#errors for full list of error codes
          if ( Number(response.statusCode) >= 400 ) {
            callback(d.errors, d);
          } else {
            callback(undefined, d);
          }
        } catch (e) {
          callback(e);
        }
github aacerox / node-rest-client / lib / node-rest-client.js View on Github external
this.proxy = function(options, callback){

        debug("proxy options",options.proxy);

            // creare a new proxy tunnel, and use to connect to API URL
            var proxyTunnel = http.request(options.proxy),
            self = this;
            
            
            proxyTunnel.on('connect',function(res, socket, head){
                debug("proxy connected",socket);

                // set tunnel socket in request options, that's the tunnel
				// itself
                options.socket = socket;

                var buffer=[],
                protocol = (options.protocol =="http")?http:https,
                clientRequest = options.clientRequest,
                requestConfig = options.requestConfig,
                responseConfig = options.responseConfig;