MongoDB - Error: Cannot find module '../build/Release/bson' - javascript

I tried to run a typescript example in the following way which caused following error:
$ mongod --dbpath /home/u/databases
$ npm install
$ tsc --sourcemap --module commonjs app.ts
$ node app.js
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
========================================================================================
= Please ensure that you set the default write concern for the database by setting =
= one of the options =
= =
= w: (value of > -1 or the string 'majority'), where < 1 means =
= no write acknowledgement =
= journal: true/false, wait for flush to journal before acknowledgement =
= fsync: true/false, wait for flush to file system before acknowledgement =
= =
= For backward compatibility safe is still supported and =
= allows values of [true | false | {j:true} | {w:n, wtimeout:n} | {fsync:true}] =
= the default value is false which means the driver receives does not =
= return the information of the success/error of the insert/update/remove =
= =
= ex: new Db(new Server('localhost', 27017), {safe:false}) =
= =
= http://www.mongodb.org/display/DOCS/getLastError+Command =
= =
= The default of no acknowledgement will change in the very near future =
= =
= This message will disappear when the default safe is set on the driver Db =
========================================================================================
/home/u/tmp/TypeScriptSamples/imageboard/app.js:9
app.configure(function () {
^
TypeError: Object function (req, res, next) {
app.handle(req, res, next);
} has no method 'configure'
at Object.<anonymous> (/home/u/tmp/TypeScriptSamples/imageboard/app.js:9:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:929:3
Furthermore, looking at db.ts I think http and url are missing in package.json file, am I right?
How is it possible to fix the above error with mongodb?

in Linux operating system first remove bson folder from node_modules and run this command:
sudo apt-get install gcc make build-essential
and then restart nodejs file such as index.js. Hope its helpful

I am using connect-mongo for sessions. I had the same problem and was because the version of connect-mongo generated an error with the version 4.0.x of mongoose. You could check each version of the dependencies you are using.

looking at db.ts I think http and url are missing in package.json file, am I right?
No. These modules are a part of core nodejs.
The source of the error is the package.json specifying minimum numbers without backward in compatible version locks. https://github.com/Microsoft/TypeScriptSamples/blob/master/imageboard/package.json#L6 I would change '>=' to be harder versions e.g. 3.x

Related

Error when import of node module 'windows' in electrons

I am updating the node module of an application made by somebody else. The module used is 'windows' and the version that was used was 0.0.8. I updated electronjs to 22 and the node module 'windows' to the latest version 0.1.2.
I am using the module, as it was used before :
const windows = require('windows');
var a = windows.registry('/RegistryPath/').SomeValueName.value;
And I am getting the error :
A JavaScript error occurred in the main process
Uncaught Exception:
TypeError: Cannot read properties of undefined (reading 'split')
at Object.
(/path/node_modules/windows/lib/runnable.js:9:29) at
Module._compile (node:internal/modules/cjs/loader:1141:14) at
Module._extensions..js (node:internal/modules/cjs/loader:1196:10)
at Module.load (node:internal/modules/cjs/loader:1011:32) at
Module._load (node:internal/modules/cjs/loader:846:12) at f._load
(node:electron/js2c/asar_bundle:2:13328) at Module.require
(node:internal/modules/cjs/loader:1035:19) at require
(node:internal/modules/cjs/helpers:102:18) at Object.
(/path/node_modules/windows/index.js:4:17) at
Module._compile (node:internal/modules/cjs/loader:1141:14)
The error location is at runnable.js:9 :
var path = require('path');
var fs = require('fs');
var exists = require('./utility').exists;
var resolve = require('./utility').resolve;
var PATH = process.env.Path.split(';').filter(function(s){ return ~s.indexOf('node') });
I tried to read the environnemental variable in Linux and I found that if I modify the code of the module 'windows' to get process.env.PATH.split(';') instead of process.env.Path.split(';') I don't get the same error. The code move forward to the next conditional loop. But the filter of the line discussed here is looking for the string 'node'. In the case of an electron app when it is package there is no node_module folder. So I also hit the same next error when the app is package; which is :
//Bugfix taken from #schmittberger
if (!exists(PATH)) {
if (process.env.NODE_PATH) {
PATH = process.env.NODE_PATH
} else {
throw new Error('No bin-PATH found');
}
}
At this point I am receiving the Error('No bin-PATH found'). I don't have enough experience to know how to fix such an issue. Even if I add the path to my node bin in the environnemental variable of Linux I will hit the same error when the app is package for Windows as there are no folder "node_modules" in the packaged app.

How to use node_modules in Deno as typescript imports?

Project: REST API for serving information stored in a neo4j graph database.
Backend: Deno
I am farely new to deno, but I'm not new to typescript, having used it in Angular frequently.
Problem: I want to use a driver to connect my neo4j database to my backend, but there is no neo4j driver made for Deno. I have scoured the internet and documentation for solutions, and have been trying to import the javascript library using the node modules import tool that has been suggested from similar answers and is supported by the deno team.
Essentially, I do npm install neo4j-driver, and then add the following code to my deno project.
Failed Solution: the javascript node modules wrapper
I implement call this function as a test for my deno server in a server.ts file.
The command I use for deno is: deno run --allow-all --unstable server.ts
neo4j_conn.ts file: (called by server.ts)
import { createRequire } from "https://deno.land/std/node/module.ts";
const require = createRequire(import.meta.url);
export async function testconnection(uri: string, user: string, password: string) {
//This is the line that fails.
var neo4j = require('neo4j-driver').v1; //this fails whether or not I include the .v1 or not.
var driver = neo4j.driver(uri, neo4j.auth.basic(user, password))
const session = driver.session()
const personName = 'Alice'
try {
const result = await session.run(
'CREATE (a:Person {name: $name}) RETURN a',
{ name: personName }
)
const singleRecord = result.records[0]
const node = singleRecord.get(0)
console.log(node.properties.name)
} finally {
await session.close()
}
await driver.close()
}
This returns the following error:
error: Uncaught (in promise) Error: Cannot find module 'net'
Require stack:
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/channel/node/node-channel.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/channel/node/index.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/channel/index.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/bolt/handshake.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/bolt/index.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/index.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver/lib/index.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/neo4jconn.ts
at Function._resolveFilename (https://deno.land/std#0.97.0/node/module.ts:273:19)
at Function._load (https://deno.land/std#0.97.0/node/module.ts:380:29)
at Module.require (https://deno.land/std#0.97.0/node/module.ts:133:21)
at require (https://deno.land/std#0.97.0/node/module.ts:1158:16)
at Object.<anonymous> (file:///mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/channel/node/node-channel.js:24:29)
at Module._compile (https://deno.land/std#0.97.0/node/module.ts:168:36)
at Object.Module._extensions..js (https://deno.land/std#0.97.0/node/module.ts:1109:10)
at Module.load (https://deno.land/std#0.97.0/node/module.ts:147:34)
at Function._load (https://deno.land/std#0.97.0/node/module.ts:413:14)
at Module.require (https://deno.land/std#0.97.0/node/module.ts:133:21)
As far as I could tell, I had done everything right, but I am a little in over my head when it comes to the typescript/js module translation.
My file structure is as follows:
package.json
package-lock.json
server.ts
neo4j_conn.ts
node_modules -|
|
:
Neo4j developer js docs: https://neo4j.com/developer/javascript/
Deno node modules "require": https://doc.deno.land/https/deno.land/std#0.97.0/node/module.ts
If you look at the Node compatibility layer README in std you will realize that right now there is no compatibility module for the net library. The compatibility will improve day by day, but take into account that Deno is not a drop in replacement for Node, but a whole new thing that won't work with Node libraries by default
https://deno.land/std#0.97.0/node

Can't install discord.js / can't find module discord.js

I attempt to install Discord.JS by running npm install discord.js and it looks like it works, but it doesn't.
I get this error when running the index.js file, but it gives an error stating that discord.js is not found. So, I try to install it again:
PS G:\My Drive\coding\node.js\bot> npm install https://github.com/discordjs/discord.js.git
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN bot#0.0.1 No repository field.
+ discord.js#12.0.2
added 15 packages from 17 contributors and audited 15 packages in 97.377s
found 0 vulnerabilities
Then I run the index.js file:
const Discord = require('discord.js');
const bot = new Discord.Client();
const botCommands = require('./commands');
const { prefix, token } = require('./cfg.json');
bot.login(TOKEN);
bot.on('ready', () => {
console.info(`Logged in as ${bot.user.tag}!`);
});
This is the result displayed in console:
PS G:\My Drive\coding\node.js\bot> node .
internal/modules/cjs/loader.js:796
throw err;
^
Error: Cannot find module './commands'
Require stack:
- G:\My Drive\coding\node.js\bot\index.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)
at Function.Module._load (internal/modules/cjs/loader.js:686:27)
at Module.require (internal/modules/cjs/loader.js:848:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (G:\My Drive\coding\node.js\bot\index.js:3:21)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10) {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'G:\\My Drive\\coding\\node.js\\bot\\index.js' ]
}
Side note: Before I ran index.js, I ran npm init -y to create a package.
P.S: English is not my first language
If you cannot find the /commands folder - are you sure it is there? - make sure it is in the folder 'G:\My Drive\coding\node.js\bot\'.
Okay. First of all, it says the module "./commands" is not found, discord.js does exist.
The reason is, you are trying to import a folder. Node.js does not work that way.
You have to delete the line with the require("./commands") and replace it with something like this:
var botCommands = fs.readdirSync('./commands/');
That will return an array of file names in that directory.
Then, go on with whatever you were doing.
Make sure you are using the correct folder and you have commands folder in G:\My Drive\coding\node.js\bot
The error is in your 3rd line ou have require the commands
If you have commands folder do this
fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
I think what you want is something like
bot.on('message', message => {
if(message.content.startsWith(prefix)) {
let rawA = message.content.slice(prefix.length).split(' ');
let cmd = rawA[0];
let rawB = rawA.join(' ');
let args = rawB.slice(cmd.length).split(' ');
let cmdFile = require(`./commands/${cmd}.js`);
cmdFile.run(bot, message, args);
}
}
But if you use this, you need this in your command file:
exports.run = async (bot, message, args) => {
//code
}
Well, Ya see, If it says "commands is not found" then it could be that your folder might be wrong, double-check the capatalization and lowercases. And if still its showing wrong.
Make sure that your commands folder is actually in this directory.
G:\\My Drive\\coding\\node.js\\bot\\index.js
Hope this helped!

twilio error 'username required'

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var TWILIO_TOKEN = "270ff32fe16828869dc30e0c6926fa9e";
var client = require('twilio')(process.env.AC55a59221acb23a5aa6f046740bb73317, process.env.TWILIO_TOKEN);
router.use(bodyParser.urlencoded({extended: true}));
router.use(bodyParser.json());
router.post('/', function(req, res) {
console.log('this is the req', req.body);
client.messages.creat({
to:'+19522209630',
from:'+17633249718',
body:'hello World'
}, function(err, data) {
if (err) {
console.log('err', err);
console.log('data', data);
}
});//en d of sendMessage
res.send(200);
});
module.exports = router;
/Users/moisesmiguelhernandez/Documents/prime/solo_project/node_modules/twilio/lib/rest/Twilio.js:101
throw new Error('username is required');
^
Error: username is required
at new Twilio (/Users/moisesmiguelhernandez/Documents/prime/solo_project/node_modules/twilio/lib/rest/Twilio.js:101:11)
at initializer (/Users/moisesmiguelhernandez/Documents/prime/solo_project/node_modules/twilio/lib/index.js:8:10)
at Object.<anonymous> (/Users/moisesmiguelhernandez/Documents/prime/solo_project/routes/sendMessage.js:6:31)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Module.require (module.js:513:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/Users/moisesmiguelhernandez/Documents/prime/solo_project/server.js:10:19)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! solo_project#1.0.0 start: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the solo_project#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/moisesmiguelhernandez/.npm/_logs/2017-07-11T15_02_02_750Z-debug.log
I am getting and error that says username is required. I am trying to use twilio. I followed a youtube video and i have it like he does. Any suggestions on how to fix this? P.S The index file is the terminal error message
Save these into a .env file at your root of your folder
TWILIO_TOKEN = "270ff32fe16828869dc30e0c6926fa9e"
TWILIO_ACCOUNT_SID = "AC55a59221acb23a5aa6f046740bb73317"
Then install
npm install dotenv --save
After that you can use these environment variables in your file like this:
require('dotenv');
var client = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_TOKEN);```
I had this same issue as well. What fixed it for me is doing
npm install dotenv
require('dotenv').config()
then I added my
TWILIO_ACCOUNT_SID=***
TWILIO_AUTH_TOKEN=***
full code:
require('dotenv').config();
const accountSid = process.env.ACCOUNT_SID;
const authToken = process.env.AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
client.calls
.create({
url: 'http://demo.twilio.com/docs/voice.xml',
to: process.env.CELL_PHONE,
from: process.env.TWIL_NUM,
})
.then(call => console.log(call.sid))
.catch(err => console.log(err));
var TWILIO_TOKEN = "270ff32fe16828869dc30e0c6926fa9e";
var TWILIO_ACCOUNT_SID = "AC55a59221acb23a5aa6f046740bb73317";
var client = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_TOKEN);
#philnash i changed it and fixed the creat typo but the terminal is still saying 'username is required'
Note -: This is not at all a good way but just a workaround. I will edit the answer as soon I will get the right way. This is just a trick which worked in my case.
const client = require('twilio')(<YOUR_ACCOUNT_SID>, <YOUR_ACCOUNT_KEY>);
basically use the keys directly instead of referencing through any variable.
Twilio developer evangelist here.
Aside from the typo in creat that Champa has pointed out in the comments, I think I know where you're going wrong. Your code currently has:
var client = require('twilio')(process.env.AC55a59221acb23a5aa6f046740bb73317, process.env.TWILIO_TOKEN);
I am guessing that it should have something like process.env.TWILIO_ACCOUNT_SID.
The account sid is effectively the username for accessing the API, which is why the error message says that.
Let me know if that helps at all.
I encountered this issue today and was getting message Error: username is required when running my twilio test. Since I am using dotenv, I have a .env file with my environment variables, and this is where I made a mistake. We have another app with the SID and TOKEN variables, so I copied them and left in the export keyword, i.e. export TWILIO_ACCOUNT_SID=..., but if using dotenv, the export keyword is not needed. I removed export and re-run my test script and it all worked, e.g.
TWILIO_ACCOUNT_SID=***
TWILIO_AUTH_TOKEN=***
I was working with a colleague when we encounter the same error. I tried almost all the solutions but didn't work for me (most of the solutions here are the same in a sense).
How we resolve this was amazing: how?
When you are using a file called .env for your environment variables, you need to double checks where you created this file
.env file must be created in your root directory. That means must be inside your project folder not inside sub-folder that is inside your project.
when you are to use it, make sure you reference the right variable. This mistake is
related to this question. such as
// index.js
// this wrong, notice process.env.AC55a59221acb23a5aa6f046740bb73317 in client variable
TWILIO_TOKEN = "270ff32fe16828869dc30e0c6926fa9e";
var client = require('twilio')(process.env.AC55a59221acb23a5aa6f046740bb73317, process.env.TWILIO_TOKEN);
this is correct process.env.TWILIO_ACCOUNT_SID
// .env
TWILIO_ACCOUNT_SID=AC55a59221acb23a5aa6f046740bb73317
Twilio Documentation
Interested in the mistake we made, it's the wrong placement of .env file.
I have ran into this error earlier so, adding to the answers above make sure the .env file is in the root directory, all spellings are correct and dotenv package is used.
I figured out the issue that I was having with this. When starting up the server, make sure that you are in the directory that contains the .env file.
The Silly mistake which I made was, I used "SMS_SID: YourSID", It must be "SMS_SID = YourSID".
In my case, everything was correct except I was using the account_sid and auth_token of test credential instead of Live credential.

Parse server clone install

I clone Repo parse server from parse-server-example and add run mongo db and also install nodejs pacakge via npm install, But when i want to run app with npm start print this error in terminal!!
How i can fix this issue ? it's about nodejs version or what?
Here is my index.js file:
// Example express application adding the parse-server module to expose Parse
// compatible API routes.
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var path = require('path');
var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'app',
masterKey: process.env.MASTER_KEY || 'master', //Add your master key here. Keep it secret!
serverURL: process.env.SERVER_URL || 'http://localhost:1337/parse', // Don't forget to change to https if needed
liveQuery: {
classNames: ["Posts", "Comments"] // List of classes to support for query subscriptions
}
});
// Client-keys like the javascript key or the .NET key are not necessary with parse-server
// If you wish you require them, you can set them as options in the initialization above:
// javascriptKey, restAPIKey, dotNetKey, clientKey
var app = express();
// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));
// Serve the Parse API on the /parse URL prefix
var mountPath = process.env.PARSE_MOUNT || '/parse';
app.use(mountPath, api);
// Parse Server plays nicely with the rest of your web routes
app.get('/', function(req, res) {
res.status(200).send('Make sure to star the parse-server repo on GitHub!');
});
// There will be a test page available on the /test path of your server url
// Remove this before launching your app
app.get('/test', function(req, res) {
res.sendFile(path.join(__dirname, '/public/test.html'));
});
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
// This will enable the Live Query real-time server
ParseServer.createLiveQueryServer(httpServer);
And by install babel-cli and run show me this:
/Users/sajad/Sites/parse/node_modules/parse-server/node_modules/babel-polyfill/lib/index.js:14
throw new Error("only one instance of babel-polyfill is allowed");
^
Error: only one instance of babel-polyfill is allowed
at Object.<anonymous> (/Users/sajad/Sites/parse/node_modules/parse-server/node_modules/babel-polyfill/lib/index.js:14:9)
at Module._compile (module.js:460:26)
at Module._extensions..js (module.js:478:10)
at Object.require.extensions.(anonymous function) [as .js] (/usr/local/lib/node_modules/babel-cli/node_modules/babel-register/lib/node.js:134:7)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/Users/sajad/Sites/parse/node_modules/parse-server/lib/ParseServer.js:9:1)
at Module._compile (module.js:460:26)
This is because this module(or more correctly, a dependency of your module) is using the const keyword which isn't available in your node version (v0.12). Full support for the const keyword came in v6 of node which arrived just this week.
Alternatively you could transpile your project using babel
If you go with the babel route you could do the following in your project root folder
npm install -g babel-cli
babel-node index.js
See babel usage page for more information on how to use babel correctly.
EDIT: In the documentation you provided it explicitly tells you that you must have at least node v4.3 and that you should run the project with the command "npm start". So i'm guessing that this project already has babel, you're just running it incorrectly and with the incorrect node version.

Categories

Resources