简体   繁体   中英

replace a function in public npm package

So I'am using a api wrapper package which again uses request for the api requests. Which works fine in most setups. But I want to use that package in a node-webkit environment and use a XHR in place of the request module. It would work with the API and works if I rewrite the module. But I don't wanna do that because of the update comfort. So forking is not an option for me. Is it possible to replace one function in a module without replacing the module.

var request = require('request');
var makeRequest = function(path, args, secure, callback, encoding) {
  var maxlen = 2048;

  var path = buildUrl(path, args);
  if (path.length > maxlen) {
    throw new Error("Request too long for google to handle (2048 characters).");
  }

  var options = {
    uri: (secure ? 'https' : 'http') + '://some.api.com' + path
  };

  if (encoding) options.encoding = encoding;
  if (config('proxy')) options.proxy = config('proxy');

  if (typeof callback === 'function') {
    request(options, function (error, res, data) {
      if (error) {
        return callback(error);
      }
      if (res.statusCode === 200) {
        return callback(null, data);
      }
      return callback(new Error("Response status code: " + res.statusCode), data);
    });
  }

  return options.uri;
};
module.exports = makeRequest;

So now i want to replace the request function oder the whole makeRequest function without changing the makeRequest. So basicly I want to overwrite the function.

edit: Add code Example.

take a look at rewire or proxyquire , that could solve your problems.

i dont see any other solution if the module you use uses makeRequest only internally, and even then this only works if makeRequest is required within the module (file) you require.

but keep in mind, this is probably bad, and should usually only be used for testing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM