[javascript] Failed to load c++ bson extension

A total node noob here. I've been trying to set up a sample node app but the following error keeps popping up every time I try to run:

node app

Failed to load c++ bson extension, using pure JS version

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: failed to connect to [#$%67890 :27017]
    at null.<anonymous> (/home/thejazeto/code/nodejs/authen/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:553:74)
    at EventEmitter.emit (events.js:106:17)
    at null.<anonymous> (/home/thejazeto/code/nodejs/authen/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:140:15)
    at EventEmitter.emit (events.js:98:17)
    at Socket.<anonymous> (/home/thejazeto/code/nodejs/authen/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js:512:10)
    at Socket.EventEmitter.emit (events.js:95:17)
    at net.js:830:16
    at process._tickCallback (node.js:415:13)

This question is related to javascript node.js express mongoose dependencies

The answer is


I have sorted the issue of getting the "Failed to load c++ bson extension" on raspbian(debian for raspberry) by:

npm install -g node-gyp

and then

npm update

I'm running Ubuntu 14.04 and to fix it for me I had to create a symlink for node to point to nodejs as described here:

nodejs vs node on ubuntu 12.04

Once I did that I re-ran these commands:

rm -rf node_modules
npm cache clean
npm install

I also got this problem and it caused my sessions not to work. But not to break either...

I used a mongoose connection.

I had this:

var mongoose = require('mongoose');
var express = require('express');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var MongoStore = require('connect-mongo')(expressSession);
...
var app = express();
app.set('port', process.env.PORT || 8080);
app.use(bodyParser);
mongoose.connect('mongodb://localhost/TEST');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  console.log('MongoDB connected');
});


app.use(cookieParser());
app.use(expressSession({
  secret: 'mysecret',
  cookie: {
    maxAge: null,
    expires: moment().utc().add('days',10).toDate(),// 10 dagen
  },
  store: new MongoStore({
  db: 'TEST',
  collection: 'sessions',
}),

Very straightforward. But req.session stayed always empty.

rm -rf node_modules
npm cache clean
npm install

Did the trick. Watch out you dont have a 'mongodb' in your package.json! Just Mongoose and connect-mongo.


On WIN 8.1

It seems I used a wrong version of mongoose in my package.json file.

I removed the line "mongoose" : "^3.8.15" from package.json.

CLI:

npm install mongoose --save

Now it says "mongoose": "^4.0.6" in package.json and the error I had is gone.


So in my case, I first tried to check under this directory /node_modules/mongoose/node_modules/, just to confirm that I have the bson module. I figured out that I did not have it in the first place, then I just run

npm install bson 

and then

npm update

All got sorted.Tried and tested in Ubuntu.


I just ran:

sudo npm install bson

and

sudo npm update

and all become ok.


Unfortunately, All the above answers are only half right.. Took a long time to figure this out..

Mongoose bson install via npm throws warning and causes the error...

npm install -g node-gyp

git clone https://github.com/mongodb/js-bson.git
cd js-bson
npm install
node-gyp rebuild

This works like magic!!


i was having same trouble tried so many options but in the last npm intall in my mean app folder worked.


I fixed it by changing line 10 of:

/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/index.js 

from:

bson = require('../build/Release/bson');

to:

bson = require('bson');

A common problem is that node-gyp requires Python 2.x and if your system's python points to 3.x, it will fail to compile bson, without warning. You can fix this by setting a python global key in your npm config that points to the 2.x executable on your system. For example, on Arch Linux:

npm config -g set python "/usr/bin/python2"

I guess you did not have the make tools available when you installed your mongodb library. I suggest you do

xcode-select --install (on a mac) or sudo apt-get install gcc make build-essential (on ubuntu)

and run

rm -rf node_modules
npm cache clean
npm install

OR just npm update based on @tobias comment (after installing build-essential)

npm update

The only thing which helps me on Windows 7 (x64): https://stackoverflow.com/a/29714359/2670121

Reinstall node and python with x32 versions.
I spent a lot of time with this error:

Failed to load c++ bson extension

and finally, when I installed module node-gyp (for building native addons) and even installed windows SDK with visual studio - nodejs didn't recognize assembled module bson.node as a module. After reinstalling the problem is gone.

Again, What does this error mean?

Actually, it's even not error. You still can use mongoose. But in this case, instead of fast native realization of bson module, you got js-realization, which is slower.

I saw many tips like: "edit path deep inside node_modules..." - which is totally useless, because it does not solve the problem, but just turned off the error messages.


In our case, the reason that the c++ version bson was not found was because we were behind a corporate proxy and something in the BSON build process needs to reach out to fetch files. When we looked in node_modules/bson/builderror.log, we saw an error like this:

gyp WARN install got an error, rolling back install
gyp ERR! configure error
gyp ERR! stack Error: connect ECONNREFUSED
gyp ERR! stack     at errnoException (net.js:904:11)
gyp ERR! stack     at Object.afterConnect [as oncomplete] (net.js:895:19)

Which suggested that the proxy might be the issue. Setting the http_proxy and https_proxy environment variables solved it.



The bson extension message is just a warning, I get it all the time in my nodejs application.

Things to check:

  • MongoDB instance: Do you have a MongoDB instance running?
  • Config: Did you correctly configure Mongoose to your MongoDB instance? I suspect your config is wrong, because the error message spits out a very weird string for your mongodb server host name..

Followint @user1548357 I decided to change the module file itself. So as to avoid the problems pointed out by the valid comments below I included my changes in a postinstall script so that I can set it and forget it and be assured that it will run when my modules are installed.

// package.json
"scripts": {
    // other scripts
    "postinstall": "node ./bson.fix.js"
},

and the script is:

// bson.fix.js
var fs = require('fs');
var file = './node_modules/bson/ext/index.js'
fs.readFile(file, 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  var result = data.replace(/\.\.\/build\/Release\/bson/g, 'bson');
  fs.writeFile(file, result, 'utf8', function (err) {
     if (err) return console.log(err);
     console.log('Fixed bson module so as to use JS version');
  });
});

I just had the same problem and literally nothing worked for me. The error was showing kerberos is causing the problem and it was one of the mongoose dependencies. Since I'm on Ubuntu, I thought there might be permission issues somewhere between the globally installed packages -- in /usr/lib/node_modules via sudo, and those which are on the user space.

I installed mongoose globally -- with sudo of course, and everything began working as expected.

P.S. The kerberos package now also is installed globally next to mongoose, however I can't remember if I did it deliberately -- while I was trying to solve the problem, or if it was there from the beginning.


For my case, I npm install all modules on my local machine (Mac), and I did not include node_modules in .gitignore and uploaded to github. Then I cloned the project to my aws, as you know, it is running Linux, so I got the errors. What I did is just include node_modules in .gitignore, and use npm install in my aws instance, then it works.


I was trying to run node on virtual machine (vagrant) shared folder. That was a problem. My host machine is Windows, installed node on Windows and worked like a charm. So if you are using virtual machine, just try to run node server on host machine.


sudo npm rebuild was what fixed it for me.


just wanted to say I also had the error

Failed to load c++ bson extension, using pure JS version

But with none of the other errors. I tried everything and turns out the mongodb drivers that I was specifying in the package.json file was incompatible with my version of MongoDB. I changed it to my latest version which was (1.4.34) and it worked!!!


easily kick out the problem by just add this line both try and catch block path: node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/index.js

bson = require('bson');  instead 

bson = require('./win32/ia32/bson');
bson = require('../build/Release/bson'); 

That is all!!!


I'm working on Docker with centOS 7, and encountered the same problem.

after looking around, and make several tries, I fixed this problem by installing mongodb, and mongodb-server

yum install mongodb mongodb-server

I don't think this is the best way to produce the minimal container. but I can limit the scope into the following packages

==============================================================================================================
 Package                          Arch              Version                          Repository          Size

==============================================================================================================
Installing:
 mongodb                          x86_64            2.6.5-2.el7                      epel                57 M
 mongodb-server                   x86_64            2.6.5-2.el7                      epel               8.7 M
Installing for dependencies:
 boost-filesystem                 x86_64            1.53.0-18.el7                    base                66 k
 boost-program-options            x86_64            1.53.0-18.el7                    base               154 k
 boost-system                     x86_64            1.53.0-18.el7                    base                38 k
 boost-thread                     x86_64            1.53.0-18.el7                    base                56 k
 gperftools-libs                  x86_64            2.1-1.el7                        epel               267 k
 libpcap                          x86_64            14:1.5.3-3.el7_0.1               updates            137 k
 libunwind                        x86_64            1.1-3.el7                        epel                61 k
 snappy                           x86_64            1.1.0-3.el7                      base                40 k

I finally corrected this error by updating my mongodb dependency version to ~2.0.36 in package.json.

 "dependencies": {
    "consolidate": "~0.9.1",
    "express": "3.x",
    "mongodb": "~2.0.36",
    "mongoose": "^4.1.12"
  }

I was able to resolve by uninstalling and reinstalling monk package. Initial install seemingly had a corrupt mongodb/bson dependency.


I fixed this problem on CentOS by

  • sudo yum groupinstall "Development Tools"
  • sudo npm install -g node-gyp
  • rm -r node_modules
  • npm cache clean
  • npm install

I just resolved that.

When you install the mongoose module by npm, it does not have a built bson module in it's folder. In the file node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/index.js, change the line

bson = require('../build/Release/bson');

to

bson = require('bson');

and then install the bson module using npm.


If the bson extension wasn't the reason, I guessed the other reason for "failed to connect" would be the user id's. So I created a new database and added a user for the database, with a password for that user (note: not mongolab account password). I updated those on my code and voila! It worked. Duh right? :D


I had this problem because I was including the node_modules folder in my Git repository. When I rebuilt the node_modules on the other system it worked. One of them was running Linux, the other OS X. Maybe they had different processor architectures as well.


Here's how I fixed the problem on Ubuntu:

  1. ln -s /usr/bin/nodejs /usr/bin/node
  2. npm install node-gyp
  3. cd node_modules/mongodb/node_modules/bson
  4. node-gyp rebuild

Inspired by @mbochynski answer, but I had to create a symbolic link first, otherwise the rebuild failed.


For me it only take to run these commands in my api directory:

rm -rf node_modules
npm cache clean 
npm install

I had the same problem on my EC2 instance. I think the initial cause was because I had a Node instance running when I installed Mongo. I stopped the Node service and then ran

sudo npm update 

inside of the top level folder of my node project. This fixed the problem and everything was just like new


On ubuntu 14.04 I needed to create a link in /usr/bin because /usr/bin/env was looking for /usr/bin/node.

ln -s /usr/bin/nodejs /usr/bin/node

The error messages can be found in the builderror.log in each directory so for the message:

[email protected] install /usr/local/lib/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson (node-gyp rebuild 2> builderror.log) || (exit 0)

look at this file for more information about the exact problem:

/usr/local/lib/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/builderror.log


I was unable to solve this

until now. First of all you have to have system packages mentioned by Pradeep Mahdevu. Those are:

xcode-select --install (on a mac) 

or

sudo apt-get install gcc make build-essential (on ubuntu)

Then I've installed node-gyp

npm install -g node-gyp 

like datadracer said but npm update also suggested by him is risky. It update all modules, which can be dangerous (sometimes API changes between versions).

I suggest going into node_modules/mongodb/node_modules/bson directory and from there use

node-gyp rebuild

That solved the problem for me.


I also encountered the same problem and I'm a Mac OSX user. Basically, you need to make sure you have installed the Xcode and also the "Command Line Tools" within the Xcode.

Xcode is free and can be downloaded over here: https://developer.apple.com/xcode/downloads/

After you have installed the Xcode, open it and click "Preference" in the pull down menu, and click the "Downloads" icon. Make sure you have the "Command Line Tools" installed.

Then run the following commands like all the other users mentioned above:

rm -rf node_modules
npm cache clean
npm install

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to express

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block jwt check if token expired Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] npm notice created a lockfile as package-lock.json. You should commit this file Make Axios send cookies in its requests automatically What does body-parser do with express? SyntaxError: Unexpected token function - Async Await Nodejs Route.get() requires callback functions but got a "object Undefined" How to redirect to another page in node.js

Examples related to mongoose

Querying date field in MongoDB with Mongoose Server Discovery And Monitoring engine is deprecated Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true Mongodb: failed to connect to server on first connect Push items into mongo array via mongoose Mongoose: findOneAndUpdate doesn't return updated document mongoError: Topology was destroyed Difference between MongoDB and Mongoose How can you remove all documents from a collection with Mongoose? E11000 duplicate key error index in mongodb mongoose

Examples related to dependencies

Upgrading React version and it's dependencies by reading package.json How do I deal with installing peer dependencies in Angular CLI? RHEL 6 - how to install 'GLIBC_2.14' or 'GLIBC_2.15'? Automatically create requirements.txt node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON] MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project npm install private github repositories by dependency in package.json Find unused npm packages in package.json Failed to load c++ bson extension Maven dependency update on commandline