Majid Hojati
Majid Hojati

Reputation: 1780

How to include nodejs package into the script

I have faced a very simple problem. I want to use a pakcage named Rbush in my javascript script in nodejs. I have installed it using npm install rbush command and when I try to use it It raises this error

ReferenceError: RBush is not defined

here is my code

const t=require('rbush');

 const tree = new RBush();
const item = {
  minX: 20,
  minY: 40,
  maxX: 30,
  maxY: 50,
  foo: 'bar'
};
tree.insert(item);

I know that I have to include it into my script and I have done that using require function but it seems that it does not add the library there.I also tried the following method but it still does not work.

const tree=require('rbush');
const item = {
  minX: 20,
  minY: 40,
  maxX: 30,
  maxY: 50,
  foo: 'bar'
};
tree.insert(item);

Upvotes: 0

Views: 143

Answers (1)

Brendan Gannon
Brendan Gannon

Reputation: 2652

Node modules export different types, so it's important to check the docs and see what you 'get' when you require the module. The usage docs for rbush are not great in this respect, but it exports a class, so your first example is almost correct.

The variable you assign the module to is how you need to reference it in your code. So instead of assigning require('rbush') to t, you probably want to assign it to RBush. (You can name it whatever you want, but if you're going to call new RBush(), then you need to use that name when you require it, const RBush = require('rbush');

const RBush = require('rbush');

const tree = new RBush();
const item = {
  minX: 20,
  minY: 40,
  maxX: 30,
  maxY: 50,
  foo: 'bar'
};
tree.insert(item);

Upvotes: 1

Related Questions