I'm tryin to build an app which requires sqlite3 Modul.
My app works fine when I run it from cmd node server.js
but when I run it from NWJS crashes and throws the error below
Uncaught Error: A dynamic link library (DLL) initialization routine failed.
\\?\C:\Users\Coder Bilall\Desktop\My Work\NWJS\GMoney\Gmoney\node_modules\sqlite3\lib\binding\napi-v3-win32-x64\node_sqlite3.node
at Object.Module._extensions..node (node:internal/modules/cjs/loader:1206:18)
at Module.load (node:internal/modules/cjs/loader:991:32)
at Function.Module._load (node:internal/modules/cjs/loader:831:14)
at Module.require (node:internal/modules/cjs/loader:1015:19)
at require (node:internal/modules/cjs/helpers:92:18)
at Object.<anonymous> (C:\Users\Coder Bilall\Desktop\My Work\NWJS\GMoney\Gmoney\node_modules\sqlite3\lib\sqlite3-binding.js:4:15)
at Module._compile (node:internal/modules/cjs/loader:1126:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1161:10)
at Module.load (node:internal/modules/cjs/loader:991:32)
at Function.Module._load (node:internal/modules/cjs/loader:831:14)
My server.js Code
const express = require('express')
const sqlite3 = require('sqlite3').verbose();
const LocalStorage = require('node-localstorage').LocalStorage;
let exec = require('child_process').exec, child;
const connectionTester = require('connection-tester');
const notifier = require('node-notifier');
const path = require('path');
const fs = require('fs');
const os = require('os');
const readline = require('readline');
const {google} = require('googleapis');
const ToCsv = require("sqlite-to-csv");
var cookieParser = require('cookie-parser')
const mailjet = require ('node-mailjet')
.connect('878dcf9b5a0ae7cf07498b6ab3d73ca7', 'c6c90ff0878e2b9640a6c342f84e142e')
const db = new sqlite3.Database('mydb.db');
const application = express();
application.use(cookieParser());
const port = 2020;
application.get('/', (req, res) => {
res.send('Hello World');
});
application.listen(port, () => {
console.log(`Example application listening at http://localhost:${port}`)
})
Please Help me 🥺🥺🥺🥺
The code failing is referencing a node binding sqlite3\lib\binding\napi-v3-win32-x64.
When you npm install some node modules will download or build files unique to your operating system (win32, linux, darwin), your architecture (x86, x64), and your Node.js ABI Version (47, 72, 88). If your globally installed version of Node is not the same as the version built in to NW.js, your module will be incompatible.
Try this:
Delete your node_modules and package-lock.json
Change your Node.js version to be the same as what is built in to that version of NW.js
Then do an npm install and see if it works
This may not be your issue, but it may resolve other issues and is quick to test.
What version of Node.js is in NW.js?
https://nwjs.io/versions.json
How do I switch Node.js versions globally?
Uninstall Node.js completely.
Install a Node Version Manager (nvm):
Linux/OSX: https://github.com/nvm-sh/nvm
Windows: https://github.com/coreybutler/nvm-windows
Windows alternative: https://github.com/marcelklehr/nodist
Consult the docs for the version of nvm you installed. Use it to install and switch to the correct Node.js version
You may also want to look at this NW.js wiki page:
https://github.com/nwjs/nw.js/wiki/Save-persistent-data-in-app#sqlite3
I am trying to set the test database for the testing purpose, but its not working.
I am trying to connect to MongoDB using mongoose, but finding problem in the connection error shows:
throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
^
MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()`is a string.
at new MongooseError (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mongoose/lib/error/mongooseError.js:11:11)
at NativeConnection.Connection.openUri (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mongoose/lib/connection.js:424:11)
at Mongoose.connect (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mongoose/lib/index.js:230:15)
at Object.<anonymous> (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/server/db/mongoose.js:5:10)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/server/models/Todo.js:1:82)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/server/tests/server.test.js:4:16)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)
at /media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mocha/lib/mocha.js:250:27
at Array.forEach (<anonymous>)
at Mocha.loadFiles (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mocha/lib/mocha.js:247:14)
at Mocha.run (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mocha/lib/mocha.js:576:10)
at Object.<anonymous> (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mocha/bin/_mocha:637:18)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Function.Module.runMain (module.js:676:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
error Command failed with exit code 1.
I am passing a valid String, but Its not working!
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI, err => {
if(err)
console.log(err);
}
);
module.exports = {
mongoose
};
Here is the Script to run mocha:
export NODE_ENV='test' && mocha server/**/*.test.js
Here is the configuration code:
const config = require('./config.json');
const env = process.env.NODE_ENV.toString() || 'development';
if(env === 'test' || env === 'development') {
const envConfig = config[env];
Object.keys(envConfig).forEach(key => {
process.env[key] = envConfig[key];
});
};
console.log(env);
Here is the config.json file:
{
"test": {
"PORT": 3000,
"MONGODB_URI": "mongodb://localhost:27017/TodoTest"
},
"development": {
"PORT": 3000,
"MONGODB_URI": "mongodb://localhost:27017/Todo"
}
}
Thanks for the help!
I think you miss importing env file.
require('dotenv').config({ path: 'ENV_FILENAME' });
To read from .env file you have to install dotenv ( npm i dotenv / yarn add dotenv)
and then just add this on top of your file.
const dotenv = require("dotenv");
dotenv.config();
I was also facing same problem after add code { useNewUrlParser: true } in mongoose.connect() method. Problem resolved.
mongoose.connect(config.DB,{ useNewUrlParser: true }));
In the server directory,
npm install dotenv
In your server.js:
If you use "type":"module" in your package.json file then,
import dotenv from 'dotenv';
import mongoose from 'mongoose';
dotenv.config();
or,
const mongoose = require('mongoose')
require('dotenv').config()
Add a .env file in the server directory,
PORT=5000
MONGO_URL= yourURL
In the server.js,
const url = process.env.MONGO_URL
mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => app.listen(PORT, () => console.log("Server up and running!")
.catch((error) => console.log(error.message)
mongoose.set('useFindAndModify', false)
i have encountered the same error, this thread didn't help... here's my solution it was simple! im using express, mongo, mongoose, and dotENV
file 1 === db.js
import mongoose from 'mongoose';
const connectDB = async ()=>{
try{
const conn = await mongoose.connect(process.env.MONGO_URI,{
//must add in order to not get any error masseges:
useUnifiedTopology:true,
useNewUrlParser: true,
useCreateIndex: true
})
console.log(`mongo database is connected!!! ${conn.connection.host} `)
}catch(error){
console.error(`Error: ${error} `)
process.exit(1) //passing 1 - will exit the proccess with error
}
}
export default connectDB
file 2= server.js
import express from 'express'
import dotenv from 'dotenv'
import connectDB from './config/db.js' // DB connection
import products from './data/products.js'
dotenv.config()
const PORT = process.env.PORT || 5000
const mode = process.env.NODE_ENV
const app = express()
connectDB() //this function connects us to the DB!!!
. . . more code…
> solution: the connectDB() expression must come after the dotenv.config() expression.
and that's it ! :)
Since error message returned UNDEFINED uri parameter, .toString() will NOT work.
You can use the String() function: String(your connection parameter).
Also, in if(env === 'test' || env === 'development') try not to use (===), it is a strict equality.
Instead try if(env == 'test' || env == 'development'). This is a loose equality. It doesn't care about the type match and will convert second operand's type to first one's type.
I ran into the same problem.
1. I saved my ATLAS_URI ID to a file called .env
2. My .env file was in the wrong directory, that's how the problem cause
3. Solution: I used "ls -a" command to make sure my .env file is in the same location as my server
try using this method worked for me.
mongoose.connect(`${process.env.MONGO_URL}`, {useNewUrlParser: true, useUnifiedTopology: true}, ()=>{
console.log("mongodb is connected")
});
there is a very small mistake Your .env file should exist in your project directory. maybe your .env file is placed in a different folder. check your .env file location
Please try the below steps
Step 1 - Install dotenv package
# with npm
npm install dotenv
# with Yarn
yarn add dotenv
Step 2 - Create a new env file e.g config.env
Step 3 - Write the below code in the config.env file
DATABASE = MONGO_URL
PORT = port_number
Step 4 - Write the below code in your main server file (in my case it is index.js)
const dotenv = require("dotenv"); //require dotenv package
dotenv.config({ path: "./config.env" }); //import config.env file
const DB = process.env.DATABASE;
const Port = process.env.PORT;
mongoose
.connect(DB, {
usenewurlparser: true,
useunifiedtopology: true,
})
.then(() => {
console.log("Successfully connected ");
})
.catch((error) => {
console.log(`can not connect to database, ${error}`);
});
This is what solved my problem. Happy Coding!
// Connect to MongoDB
mongoose.connect('mongodb://yourusername:yourpassword#ds121825.mlab.com:11025/yourmongodb', {useNewUrlParser: true});
mongoose.connection.once('open', function(){
console.log('Conection has been made!');
}).on('error', function(error){
console.log('Error is: ', error);
});
I had the same problem, but then I realized that I saved the .env file as .env.txt which caused the issue. I deleted the file and created another file without .txt at the end and everything worked find.
I hope this helps.
Dhiya Aljaradi
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
Always put useNewUrlParser:true before putting the useUnifiedTopology:true, and then the rest.
i have taken this error message, you have to declare .env file after installing dotenv package. if you declare file before installing package , variable will be undefined
If you are getting the same error, Even after configuring dotenv and setting everything step by step, then you have to restart your MongoDB and server and wait for some time.
Look at the images, I have done nothing, just restarted MongoDB, and the server
sometimes it's a mongo server issue
I had a similar issue, fixed by adding this code snippet.
mongoose.connect(config.DB,{ useMongoClient:true });
Make sure that you have the .env file with the constants that you are using defined.
I had same error, for me it was because I was trying to use environment variables in globalSetup which had the file for initiating db connection.. mongoose.connect(global.__MONGO_URI__
Apparently, environment variables are not initialised yet in globalSetup so I had to move the code somewhere else, either to setupFilesAfterEnv or by using Async Test Environment
const db = process.env.MONGO || 'test'
mongoose.connect(db, {
useNewUrlParser: true,
useUnifiedTopology:true,
useCreateIndex: true
}).then(()=>{
console.log("conected to mongodb");
}).catch(error => {
console.log("mongo error",error);
})
just change the env
const db = process.env.MONGO || 'test'
in case you've forgotten to import/require dotenv, then you can run dotenv before running your app using --require dotenv/config
node --require dotenv/config index.js // regular node command
// nodemon to restart application whenever a file gets changed
nodemon --require dotenv/config index.js
// integrate with babel-node if you're using latest JS features like import/export
nodemon --require dotenv/config index.js --exec babel-node
No need to require dotenv and call config function within codebase. Enjoy!
What I was doing wrong was I created js file to store the key:
module.export = {
MONGOURI : "Your Key"
}
and from my app.js I was fetching the key with different keyname like
const {MongoUri} = require('./keys')
after changing MongoUri to MONGOURI , it worked fine.
If we don't want to define the path of the .env file like this,
require('dotenv').config({ path: 'ENV_FILENAME' });
we can place .env file in the same place as our main file, which was App.js in my case. So we could directly write
require('dotenv').config()
I came across this same issue and here is my fix:
the process.env.MONGODB_URL should be in a string.
Check it out
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('process.env.MONGODB_URI', err => {
if(err)
console.log(err);
}
);
module.exports = {
mongoose
};
my .env file was named .dotenv by mistake.
after changing it to .env everything worked 👌
i had a similar issue, Make sure that you have the .env in "/" (next to your package.json file).if do not want to require and load dotenv in your application code or still have an issue run your server through:
node -r dotenv/config your_script.js.
otherwise, if your file containing environment variables is located elsewhere, you have to use path module:
common js: require('dotenv').config({ path: '/custom/path/to/.env' })
ES:dotenv.config({ path: '/custom/path/to/.env' })
after using
require("dotenv").config(); or import dotenv from "dotenv";
dotenv.config(); put your .env file in the same folder as server file
You can check for the ".env" file in your folder has the exact name, else it won't work.
If you have named the ".env" file something else then please change it.
I have faced the same problem. I solved it easily.
Step 1: npm install dotenv
Step 2: require('dotenv').config()
Step 3: Create a .env file
Step 4: Push Into this code dot env (.env) file DB_USER = ******** and DB_PASS = ********
Step 5:
const dbURL = mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}#techbd71.5ewxj.mongodb.net/enter
table name here?retryWrites=true&w=majority
mongoose.connect(dbURL, {useNewUrlParser: true, useUnifiedTopology: true})
.then(()=>console.log('DB Ok'))
.catch(err => console.log(err))
I also got stuck with same problem so I fixed it like this..
mongoose.connect('mongodb+srv://username:password#cluster0.h9zpqsi.mongodb.net/?retryWrites=true&w=majority',{
useNewUrlParser:true,})
// Using MONGO_URI instead of using process.env.MONGO_URI
When I run node server.js in the command line I get this error:
C:\Users\Shaelyn\WebstormProjects\CIT366Projects\cms>node server.js
C:\Users\Shaelyn\WebstormProjects\CIT366Projects\cms\node_modules\express\lib\router\index.js:458
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a Object
at Function.use (C:\Users\Shaelyn\WebstormProjects\CIT366Projects\cms\node_modules\express\lib\router\index.js:458:13)
at Function.<anonymous> (C:\Users\Shaelyn\WebstormProjects\CIT366Projects\cms\node_modules\express\lib\application.js:220:21)
at Array.forEach (<anonymous>)
at Function.use (C:\Users\Shaelyn\WebstormProjects\CIT366Projects\cms\node_modules\express\lib\application.js:217:7)
at Object.<anonymous> (C:\Users\Shaelyn\WebstormProjects\CIT366Projects\cms\server.js:34:5)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
I think part of it might be that the mongoose.connect is an unresolved function. Does anyone know how to fix this error?
This is my code:
// Get dependencies
var express = require('express');
var path = require('path');
var http = require('http');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
// import the routing file to handle the default (index) route
var index = require('./server/routes/app');
const messageRoutes = require('./server/routes/messages');
const contactRoutes = require('./server/routes/contacts');
const documentRoutes = require('./server/routes/documents');
// establish a connection to the mongo database
mongoose.connect('mongodb://localhost:27017/cms');
var app = express(); // create an instance of express
// Tell express to use the following parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(logger('dev')); // Tell express to use the Morgan logger
// Tell express to use the specified director as the
// root directory for your web site
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/', index);
app.use('/messages', messageRoutes);
app.use('/contacts', contactRoutes);
app.use('/documents', documentRoutes);
// Define the port address and tell express to use this port
const port = process.env.PORT || '3000';
app.set('port', port);
// Create HTTP server.
const server = http.createServer(app);
// Tell the server to start listening on the provided port
server.listen(port, function() {console.log("API running on localhost: " +
port)});
Your mongoose.connect call is working fine. If it wasn't then you would definitely have received a PromiseRejection for connection failure and a deprecated warning for UnhandledPromiseRejection.
Still you can ensure that by adding few event listeners on mongoose events.
mongoose.connect('mongodb://127.0.0.1:27017');
mongoose.connection.on('connected', () => console.log('Connected'));
mongoose.connection.on('error', () => console.log('Connection failed with - ',err));
Coming to your error. This is more likely to happen when you have passed anything but a function as your handler to your app.use or router.use call. app.use and router.use both require functions to be passed to them which later express would call whenever a request arrives.
The import statements on top of your code, where you require your routers are most likely to be the culprits here as by default every module.exports is an object.
I need to look into your router files to further dig into the problem, but you may yourself verify the same. Just see if the module.exports of every router file imported points to a express router instance - express.Router(). This way every route file will export a configured express.Router() instance which will be a function attached to app via app.use() call.
Replace mongodb://localhost:27017 with mongodb://127.0.0.1:27017
To capture the exact error please follow the below approach.
const mongoose = require('mongoose');
const url = "mongodb://127.0.0.1:27017";
mongoose.connect(url).then(() => {
console.log("Connected to Database");
}).catch((err) => {
console.log("Not Connected to Database ERROR! ", err);
});
Im learning Node and trying create a server using Express and connecting it to a postgres db and keep getting the following when I run node server.js:
events.js:72
throw er; // Unhandled 'error' event
^
error: role "username" does not exist
at Connection.parseE (/Users/rs/Desktop/Jobletics/node_modules/pg/lib/connection.js:526:11)
at Connection.parseMessage (/Users/rs/Desktop/Jobletics/node_modules/pg/lib/connection.js:356:17)
at Socket.<anonymous> (/Users/rs/Desktop/Jobletics/node_modules/pg/lib/connection.js:105:22)
at Socket.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:764:14)
at Socket.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:426:10)
at emitReadable (_stream_readable.js:422:5)
at readableAddChunk (_stream_readable.js:165:9)
at Socket.Readable.push (_stream_readable.js:127:10)
my server.js file looks like this:
// app dependencies
var express = require("express");
var Sequelize = require("sequelize");
var bodyParser = require('body-parser');
var morgan = require('morgan');
var app = express();
//middleware
app.use(bodyParser());
app.use(morgan('dev'));
//sequalize initialization
var sequelize = new Sequelize("postgres://username:password#localhost:5432/jobletics");
var employerRoute = require("./routes/employer")(sequelize);
//sync the model with the database
sequelize.sync().success(function (err) {
app.get("/employer", employerRoute.get);
app.post("/employer", employerRoute.create);
app.listen(5000);
});
I have postgres running. Do I need to create a new db in the command-line then run $psql to create username/password? Shouldn't the db get created automatically?
You can use
var sequelize = new Sequelize("postgres://username:password#localhost:5432/jobletics");
for connecting to postgresql database, but sequelize does not create nor user nor database for you. You must do it yourself. Use createuser and createdb postgres utilities to create them, or user -c flag of psql command. You also must have privilege to do it, so in the next example commands run using postgres user:
su postgres -c "psql -U postgres -c \"CREATE USER username WITH ENCRYPTED PASSWORD 'password'\""
su postgres -c "psql -U postgres -c \"CREATE DATABASE jobletics WITH OWNER=username ENCODING='UTF8'\""
Although Sequelize does not have a method to create databases, you can use the create query method to execute a custom method.
But the catch is the following,
You need to "connect to a database" to execute any command
Here you can't do that because it's that database creation command that you would want to create in the first place.
There's one simple way to overcome this. Postgress has two inbuilt template DBs that cannot be dropped called template0 and template1 respectively. More on template databases here
So all you have to do is connect to template1 (not template0) in your connection string
const sequelize = new Sequelize('postgres://username:password#localhost:5432/template1')
and execute the sequelize query method with the create query command
const createQuery = "CREATE DATABASE YOUR_DB_NAME WITH OWNER = postgres ENCODING = 'UTF8' LC_COLLATE = 'English_United States.1252' LC_CTYPE = 'English_United States.1252' TABLESPACE = pg_default CONNECTION LIMIT = -1;"
sequelize.query(createQuery)
.then(() => console.log("DB created"))
.catch(err => console.log("error creating DB", err))
I have not seen the database getting created automatically. When I use sequelize.js, i normally run it within a vm which has a puppet manifest to assert that the database already exists.
Also, when it comes to connecting to the db, I would normally do it like so as I think it is easier to read:
var Sequelize = require("sequelize");
var sequelize = new Sequelize(
"dbName",
"username",
"password",
{
"dialect": "postgres",
"port": 5423
}
);
Finally, make sure that postgres existing in your package.json, if is doesn't you will have to run the following:
npm install --save pg pg-hstore