NodeJs: Difference between new Require object (Request) ? errors in Webstorm IDE

StackOverflow https://stackoverflow.com/questions/23442698

  •  14-07-2023
  •  | 
  •  

Pregunta

I have the following code, and I have created the require with "new" and without. Both work. but in Webstorm without the "new" it complains that "on" and "pipe" are unresolved. Of course, it still runs.

What is the correct way? Most examples I see without the "new" but this causes issues with Webstorm and code completion etc.

var request = require('request');
var result = new request('http://www.google.com/'); // passing new fixes webstorm

result.pipe(process.stdout);


result.on('data', function(d) {
   console.log('>! data arrived : ' + d);
});

result.on('end', function() {
    console.log('>! end arrived : ');
});
¿Fue útil?

Solución

I know it's not nice when WebStorm underlines correct code, but I'm afraid it doesn't know all about Node.js.

function request (uri, options, callback) {
  if (typeof uri === 'undefined') throw new Error('undefined is not a valid uri or options object.')
  if ((typeof options === 'function') && !callback) callback = options
  if (options && typeof options === 'object') {
    options.uri = uri
  } else if (typeof uri === 'string') {
    options = {uri:uri}
  } else {
    options = uri
  }

  options = copy(options)

  if (callback) options.callback = callback
  var r = new Request(options)
  return r
}

request internally creates a new Request object, so using the function as a constructor function is creating an object which will be good only for garbage collecting.

You could explicitly call new request.Request({uri: '...'}) and look whether WebStorm is quiet then (I suppose it will be - haven't tried it). A bit nicer would it look like when you require like var Request = require('request').Request.

BTW I wonder why WebStorm doesn't complain calling a constructor which is not camel-cased...

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top