React-Native assembleRelease fails for task ':app:bundleReleaseJsAndAssets' - javascript

When I run ./gradlew assembleRelease build is failed with this error:
Error:Execution failed for task ':app:bundleReleaseJsAndAssets.
> A problem occurred starting process 'command 'node'
I searched on the internet and found some topics about it, but I couldn't solve my problem.
React-Native version: 0.54.0
EDIT:
Now I'm running ./gradlew assembleRelease --info from the terminal instead of Android Studio and I get different error. Here is the result:
> Task :app:processReleaseResources
Putting task artifact state for task ':app:processReleaseResources' into context took 0.007 secs.
file or directory '**/android/app/libs', not found
file or directory '**/node_modules/appcenter-crashes/android/libs', not found
file or directory '**/node_modules/appcenter-analytics/android/libs', not found
file or directory '**/node_modules/appcenter/android/libs', not found
file or directory '**/node_modules/react-native-interactable/lib/android/libs', not found
file or directory '**/node_modules/react-native-navigation/android/app/libs', not found
file or directory '**/android/app/libs', not found
file or directory '**/node_modules/appcenter-crashes/android/libs', not found
file or directory '**/appcenter-analytics/android/libs', not found
file or directory '**/node_modules/appcenter/android/libs', not found
file or directory '**/node_modules/react-native-interactable/lib/android/libs', not found
file or directory '**/node_modules/react-native-navigation/android/app/libs', not found
Executing task ':app:processReleaseResources' (up-to-date check took 0.035 secs) due to:
Task has failed previously.
All input files are considered out-of-date for incremental task ':app:processReleaseResources'.
Unable do incremental execution: full task run
file or directory '**/android/app/libs', not found
file or directory '**/node_modules/appcenter-crashes/android/libs', not found
file or directory '**/node_modules/appcenter-analytics/android/libs', not found
file or directory '**/node_modules/appcenter/android/libs', not found
file or directory '**/node_modules/react-native-interactable/lib/android/libs', not found
file or directory '**/node_modules/react-native-navigation/android/app/libs', not found
file or directory '**/android/app/libs', not found
file or directory '**/node_modules/appcenter-crashes/android/libs', not found
file or directory '**/node_modules/appcenter-analytics/android/libs', not found
file or directory '**/node_modules/appcenter/android/libs', not found
file or directory '**/node_modules/react-native-interactable/lib/android/libs', not found
file or directory '**/node_modules/react-native-navigation/android/app/libs', not found
Aapt2QueuedResourceProcessor is using **/Android/sdk/build-tools/26.0.2/aapt2
Failed to execute aapt
com.android.ide.common.process.ProcessException: Failed to execute aapt
*
*
*
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:processReleaseResources'.
> Failed to execute aapt
It seems gradle is looking for libs folder in all modules, but there are no libs folders in the node modules. It's true, but I don't know why gradle is looking for libs folder.

First:
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
finally build:
./gradlew assembleRelease -x bundleReleaseJsAndAssets

Looks like you haven't made a js bundle so please make a bundle first by using command :-
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
then in your project directory
cd android
Clean your gradle
./gradlew clean
and make a build finally
./gradlew assembleDebug
Try this.
Hope it will helps you.

For me the creating the bundle failed, but I noticed this comment by Sahin Elidemir:
just ./gradlew assembleRelease -x bundleReleaseJsAndAssets saved me.
It almost worked for me. What worked at the end was (notice the app:, which for me it fails without, and a clean for good measure):
./gradlew clean app:assembleRelease -x bundleReleaseJsAndAssets

Just using ./gradlew --stop and then ./gradlew assembleRelease worked for me.

I had the same problem, the solution was :
cd to yourApp/android folder
run this
./gradlew --stop
and then
./gradlew assembleRelease
This gonna build your app.
After build is done, go to see your application(apk).
android\app\build\outputs\apk\release

This is working for me, Please follow the below steps:-
1) Stop Running Gradle
$ cd RectNatoveProjectName & cd android (Open your project and go to android folder)
$ ./gradlew --stop (Run this command to stop old running Gradle service )
2) Update the android app build gradle
project.ext.react = [
nodeExecutableAndArgs : ["/usr/local/bin/node"]
];
3) Get Node details
$ which node
> (Result will be like "/usr/username/.nvm/versions/node/v10.7.0/bin/node")
4) Link node (very imp step copy the above result in step 3)
- ln -s /usr/username/.nvm/versions/node/v10.7.0/bin/node /usr/local/bin/node
5) If Step - 4 return file exist
- then to go the folder /usr/local/bin/ and delete the "node" file and perform the step -4 again.
6) If Step - 4 run successfully then this node issue will be resolved.

I now this is late. may be this will help somebody.
For me it i had to upgrade to latest react-native-sentry.
apply from: "../../node_modules/react-native-sentry/sentry.gradle"
was causing problem

The steps above really helped.
Here's the scripts that work for us with react-native 0.55.3.
Run the android-build command locally or CI to generate an APK.
/packages.json (react-native):
"android-bundle": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res",
"android-release-fix": "node ./android-release-gradle-fix.js",
"android-build": "yarn killbin && yarn android-clean && yarn android-release-fix && yarn android-bundle && cd android && ./gradlew assembleRelease -x bundleReleaseJsAndAssets --info",
"android-clean": "cd android && ./gradlew clean",
"killbin": "rm -rf ./node_modules/.bin",
android-release-gradle-fix.js:
const fs = require('fs')
// Fix issues with Android resources like duplicate files
// CI: run install with --unsafe-perm option
// https://stackoverflow.com/questions/47084810/react-native-android-duplicate-file-error-when-generating-apk
try {
var curDir = __dirname
var rootDir = process.cwd()
var file = `${rootDir}/node_modules/react-native/react.gradle`
var dataFix = fs.readFileSync(`${curDir}/android-react-gradle-fix`, 'utf8')
var data = fs.readFileSync(file, 'utf8')
var doLast = "doLast \{"
if (data.indexOf(doLast) !== -1) {
throw "Already fixed."
}
var result = data.replace(/ \/\/ Set up inputs and outputs so gradle can cache the result/g, dataFix);
fs.writeFileSync(file, result, 'utf8')
console.log('Done')
} catch (error) {
console.error(error)
}
android-react-gradle-fix
doLast {
def moveFunc = { resSuffix ->
File originalDir = file("${resourcesDir}/drawable-${resSuffix}")
if (originalDir.exists()) {
File destDir = file("${resourcesDir}/drawable-${resSuffix}-v4")
ant.move(file: originalDir, tofile: destDir)
}
}
moveFunc.curry("ldpi").call()
moveFunc.curry("mdpi").call()
moveFunc.curry("hdpi").call()
moveFunc.curry("xhdpi").call()
moveFunc.curry("xxhdpi").call()
moveFunc.curry("xxxhdpi").call()
}
// Set up inputs and outputs so gradle can cache the result
/android/build.gradle:
buildscript {
ext {
buildToolsVersion = "27.0.3"
minSdkVersion = 21
compileSdkVersion = 27
targetSdkVersion = 27
supportLibVersion = "27.1.1"
googlePlayServicesVersion = "15.0.1"
androidMapsUtilsVersion = "0.5+"
}
...
subprojects {
afterEvaluate {project ->
if (project.hasProperty("android")) {
android {
compileSdkVersion 27
buildToolsVersion '27.0.3'
}
}
}
}
/android/app/build.gradle:
dependencies {
implementation project(':amazon-cognito-identity-js')
implementation project(':appcenter-push')
implementation project(':react-native-fbsdk')
implementation(project(':react-native-google-signin')) {
exclude group: "com.google.android.gms" // very important
}
implementation project(':react-native-image-picker')
implementation project(':react-native-vector-icons')
implementation project(':react-native-sentry')
implementation project(':react-native-maps')
implementation "com.google.android.gms:play-services-auth:$googlePlayServicesVersion" // Google signin
implementation project(':react-native-sentry')
implementation(project(':react-native-maps')) {
exclude group: 'com.google.android.gms', module: 'play-services-base'
exclude group: 'com.google.android.gms', module: 'play-services-maps'
}
implementation "com.google.android.gms:play-services-base:$googlePlayServicesVersion"
implementation "com.google.android.gms:play-services-maps:$googlePlayServicesVersion"
implementation "com.google.firebase:firebase-core:15.0.2"
implementation "com.google.firebase:firebase-messaging:15.0.2"
implementation project(':react-native-vector-icons')
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "com.android.support:appcompat-v7:$supportLibVersion"
implementation 'com.facebook.react:react-native:+'
// implementation "com.android.support:$supportLibVersion"
}

if you are using macOS and using react native try this:
brew install react-native-cli
./gradlew --stop
./gradlew clean
./gradlew aRor ./gradlew assembleRelease

I did it like this and it works:
Removed node modules (you can do it by running this command rm -rf node_modules)
Run npm install or yarn install
Then run ./gradlew clean && ./gradlew app:assembleRelease or ./gradlew app:assembleDebug

For me:
OS: Windows.
I just copied the .keystore file to android\app.
cd android && gradlew --stop then gradlew assembleRelease.

This error also occurs when you have stacked your project inside many folders
Try copying your project folder into one of your hard drives without putting that project into any folder.

I was using the wrong image size (i.e image#5x.png) which caused me this problem. When I deleted that image#5x.png file...it worked!!

As of RN 0.58, for CI builds the commands is as follows:
First create directories:
mkdir -p app/build/generated/assets/react/production/release/ && mkdir -p app/build/generated/res/react/production/release
Next:
node ../node_modules/react-native/local-cli/cli.js bundle --platform android --dev false --entry-file index.android.js --bundle-output app/build/generated/assets/react/production/release/index.android.bundle --assets-dest app/build/generated/res/react/production/release --max-workers 1 --reset-cache
Also you may also want to add for your production builds according to this;
--minify true
Taken from RN's source
NOTE: We added --max-workers 1 not to deplete CI resources since they are limited to lower numbers (mem&cpu).

Consider checking all your JS (React native). I faced this issue coz have a coding error in the JS file (React native).

if you are running these commands in VS code,
Just open the project in cmd (administrator mode) in android folder run
$ gradlew clean
$ gradlew assembleRelease

I had the same problem. In my case, after a few hours, I saw this on GitHub: https://github.com/getsentry/sentry-react-native/issues/578#issuecomment-503428032.
I had renamed the project on Sentry. If you renamed the project on, update the android/sentry.properties and ios/sentry.properties file.
defaults.url=https://sentry.io/
defaults.org=yourorg
defaults.project=newprojectname
auth.token=🔑
And that's it

Solution :
1- android\app\build.gradle
project.ext.react = [
enableHermes: false,
]
2-
cd android
gradlew clean
3- gradlew bundleRelease

Check your project to make sure that you didn't name any of your folders with spaces in between.
For me, there was a space in the name of my project's parent folder.
When I remove the space (from Source Codes to codes) my build was successful.

In my case
npx was not able to go into the correct directory due to a space in the parent directory name
example :-
D:\dk\native\aiims raipur\aiimsraipur
Removed space from directory -> aiims raipur to aiims_raipur
Build works fine.

try android/app/build.gradle
def enableSeparateBuildPerCPUArchitecture = false
in new rn versions it is set to true
then
gradlew clean
gradlew assembleRelease

In my case,
The solution is so simple,
your project ancestors folder names should not contain spaces, like:
D:\Documents\React Native\MyRNProjectTest
in this "React Native" folder has space in it, removing the space from folder name could solve the problem, like this "ReactNative".

Related

Error: Cannot find module ‘/opt/Ferdi/resources/app.asar/node_modules/#meetfranz/theme/lib/index.js’

I’m collaborating with the programmers involved in the ferdi project.
https://getferdi.com/
Ferdi motto is :"All your messaging services in one place ". Infact it is like franz and it works on a lot of oses,such as mac os M1,windows,ubuntu x64 bit. And we are trying to make it work also on the arm64 / jetson nano / Tegra. Unfortunately on this os it does not work correctly because we have a javascript error that we aren’t able to fix. This is how to reproduce it :
[ `root#zi-desktop` ](mailto:root#zi-desktop) `:~/Desktop/zi/Work/I9/Virt/dockers/arm64/ferdi2# ferdi`
`[21980:0709/185715.104381:FATAL:electron_main_delegate.cc(252)] Running as root without --no-sandbox is not supported. See` [ `https://crbug.com/638180` ](https://crbug.com/638180) `.Trace/breakpoint trap`
[ `root#zi-desktop` ](mailto:root#zi-desktop) `:~/Desktop/zi/Work/I9/Virt/dockers/arm64/ferdi2# ferdi --no-sandbox`
`A JavaScript error occurred in the main processUncaught Exception:Error: Cannot find module` [ `'/opt/Ferdi/resources/app.asar/node_modules/#meetfranz` ](mailto:'/opt/Ferdi/resources/app.asar/node_modules/#meetfranz) `/theme/lib/index.js'.
Please verify that the package.json has a valid "main" entryat
tryPackage (internal/modules/cjs/loader.js:310:19)at
Function.Module._findPath (internal/modules/cjs/loader.js:523:18)at
Module._resolveFilename (internal/modules/cjs/loader.js:874:27)at
Function.n._resolveFilename (electron/js2c/browser_init.js:257:1128)at
Module._load (internal/modules/cjs/loader.js:732:27)at Function.f._load
(electron/js2c/asar_bundle.js:5:12913)`
(running as normal user gives the same error)
Basically we use a docker container like this to produce the deb packages that we will install on the os . Below u can see the Dockerfile for arm64 / tegra / jetson nano :
`FROM node:fermium-buster`
`LABEL Author="ZioMario <` [ `marietto2008#gmail.com` ](mailto:marietto2008#gmail.com) `>"`
`LABEL Title="arm64/ferdi"`
`# Enviorment variables`
`#ARG username=ferdi-arm64-builder`
`#ENV HOME /home/$username`
`ENV DEBIAN_FRONTEND=noninteractive`
`ENV LC_ALL=C.UTF-8`
`ENV LANG=C.UTF-8`
`ENV PATH="/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin:/usr/local/lib:/usr/include:/usr/share"`
`#ENV HW="GPU"`
`#ENV TERM xterm`
`ENV USE_SYSTEM_FPM=true`
`ENV PREVAL_BUILD_INFO_PLACEHOLDERS=true`
`#RUN apt-get update && apt-get install -y ca-certificates curl netbase wget tzdata rpm git xz-utils nano gedit ruby gem`
`RUN apt-get update && apt install -y rpm ruby gem && gem install fpm --no-ri --no-rdoc --no-document`
`WORKDIR /ferdi`
`RUN git clone` [ `https://github.com/getferdi/ferdi.git` ](https://github.com/getferdi/ferdi.git) `. && git submodule update --init --recursive`
`RUN npx lerna bootstrap`
`RUN cd recipes && npm i && npm run package`
`RUN npm run build`
It is working everywhere,except on the jetson nano. do u have some ideas about how to fix it ? thanks.
In these cases usually try to delete the package-lock.json and node_modules, then try to run npm install again.
Also looks like you have a problem related to the "main" prop in package.json. The main property of a package.json is a direction to the entry point to the module that the package.json is describing.
For example in a Node.js application, when the module is called via a required statement, the module's exports from the file named in the main property will be what's returned to the Node.js application.

React native project doesn't run iOS

I've started React-Native programing recently. When I want to create a new project based on a guidence of "https://reactnative.dev/docs/environment-setup" and want to run in xcode 12.5 this error is shown:
bash: Progects/Trading: No such file or directory
Command PhaseScriptExecution failed with a nonzero exit code
enter image description here
I' ll be thankfull of guiding me
Make sure you installed pods. If you already installed then delete the pods folder and podfile.lock inside the ios.
Run this command on your terminal:
cd ios && pod install && cd ..
Open your ios folder through finder and open .xcworkspace file and run from their

Generate apk using gradle & Nodejs

I am trying to generate apk files using Nodejs along with Gradle with the NodeJs sync process and the following code:
const exec = require('child_process').execSync;
exec(`cd ~/appFolder && ./gradlew assembleRelease`);
Now please note that when I execute:
cd ~/appFolder && ./gradlew assembleRelease
from the command line, it works perfectly and I get build successful. But when I run the javascript above, I get the following error:
FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring project ':app'.
> SDK location not found. Define location with sdk.dir in
the local.properties file or with an ANDROID_HOME environment variable.
Note that I did set ANDROID_HOME and the local.properties file exist in the app folder.
Thank you very much.

PDF file creation using html-pdf is not working in my deployment server?

I am using html-pdf npm module to create a pdf file, everything is working fine in my local environment (mac, windows). But when we deployed the same code in our amazon ec2 server create() of html-pdf is not able to create file nor giving me any error. I almost tried all possible ways by exception handling, absolute path etc. None of them work. Can anyone help me on this please. my code is
function generatePdf(content, options, callback) {
var fileName = new Date().getTime() + Math.random() + '.pdf';
pdf.create(content, options).toFile('../uploads/' + fileName, function(error, response) {
if (error) {
callback(error);
} else {
callback({
fileName: fileName,
filePath: response.filename
});
}
});
}
Here error is {} and the response is {}
There is absolutely nothing wrong with the above code. However, the reason why html-pdf lib is not throwing any error nor creating a file while pdf.create(...).toFile is due to the errors in html-pdf installed version in your environment. We can determine it by checking
npm list html-pdf and if returns anything like npm ERR! code 1 then do
npm uninstall html-pdf and then do again
npm install html-pdf
and repeat above step to make sure there are no errors in current installed version of html-pdf.
I'd the same problem and after searching on google, following through the posts on StackOverflow & GitHub threads doesn't work out for me.
Later I realize and checked for Phantomjs and got that was missing on the server.
I installed using the below command on ubuntu server.
sudo apt-get install phantomjs
Have fun if this works for you.
I had a same issue. We were using docker for the deployment.i.e, "node:12.17.0-alpine"
I added following on Dockerfile
ENV PHANTOMJS_VERSION=2.1.1
ENV NPM_CONFIG_PREFIX=/home/node/.npm-global
ENV PATH=$PATH:/home/node/.npm-global/bin
RUN apk update && apk add --no-cache fontconfig curl curl-dev && \
cd /tmp && curl -Ls https://github.com/dustinblackman/phantomized/releases/download/${PHANTOMJS_VERSION}/dockerized-phantomjs.tar.gz | tar xz && \
cp -R lib lib64 / && \
cp -R usr/lib/x86_64-linux-gnu /usr/lib && \
cp -R usr/share /usr/share && \
cp -R etc/fonts /etc && \
curl -k -Ls https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-${PHANTOMJS_VERSION}-linux-x86_64.tar.bz2 | tar -jxf - && \
cp phantomjs-2.1.1-linux-x86_64/bin/phantomjs /usr/local/bin/phantomjs
A few things you can use to debug the issue.
Can you use try-catch method instead of if-else? and console.log(error) in catch.
Use __dirname instead of relative file address. i.e; __dirname + '/uploads' instead of '../uploads/'
Try using fs module to create a writeable stream
it seems all the problem is in this line. Commenting it makes the error go away:
# System default
openssl_conf = default_conf
/etc/ssl/openssl.cnf
html-pdf is a npm library which is used to convert HTML file to pdf.
Install html-pdf globally using this command:
npm install -g html-pdf

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)
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
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.
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 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.
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"
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.
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
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.
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!!!
sudo npm rebuild was what fixed it for me.
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"
}
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!!
For me it only take to run these commands in my api directory:
rm -rf node_modules
npm cache clean
npm install
I just ran:
sudo npm install bson
and
sudo npm update
and all become ok.
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..
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 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');
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.
Here's how I fixed the problem on Ubuntu:
ln -s /usr/bin/nodejs /usr/bin/node
npm install node-gyp
cd node_modules/mongodb/node_modules/bson
node-gyp rebuild
Inspired by #mbochynski answer, but I had to create a symbolic link first, otherwise the rebuild failed.
i was having same trouble tried so many options but in the last npm intall in my mean app folder worked.
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.
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
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.
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.
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
For Windows 7.1, these directions helped me to fix my build environment:
https://github.com/mongodb/js-bson/issues/58#issuecomment-68217275
http://christiankvalheim.com/post/diagnose_installation_problems/
I was able to resolve by uninstalling and reinstalling monk package.
Initial install seemingly had a corrupt mongodb/bson dependency.
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');
});
});
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!!!
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.

Categories