I am experience a Module Not Found error for an NPM package that is installed and appears to be present in the node_modules folder. Is something missing in the underlying package itself?
Here is my package.json:
{
"name": "cmtest",
"version": "0.0.0",
"description": "cmtest",
"main": "server.js",
"author": {
"name": "Andrew"
},
"dependencies": {
"cloudmersive": "^1.3.2"
}
}
And then I am calling a require:
'use strict';
var http = require('http');
var Cloudmersive = require('cloudmersive');
var port = process.env.PORT || 1337;
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
var api = new Cloudmersive.BarcodeLookupApi()
var value = "value_example"; // {String} Barcode value
var callback = function (error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
api.barcodeLookupEanLookup(value, callback);
}).listen(port);
But I am getting this error:
"Cannot find module 'cloudmersive'"
"Error: Cannot find module 'cloudmersive'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:571:15)
at Function.Module._load (internal/modules/cjs/loader.js:497:25)
at Module.require (internal/modules/cjs/loader.js:626:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (c:\users\andrew\documents\visual studio 2017\Projects\cmtest\cmtest\server.js:3:20)
at Module._compile (internal/modules/cjs/loader.js:675:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:689:10)
at Module.load (internal/modules/cjs/loader.js:589:32)
at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
at Function.Module._load (internal/modules/cjs/loader.js:520:3)"
Any ideas? Is there something wrong with the package itself? Is it a development/configuration issue on my part?
The package cloudmersive is installed with NPM and shows up in the node_modules folder. I also tried using nvm to switch between several different versions.
Underlying package source is here: https://github.com/Cloudmersive/Cloudmersive.APIClient.Javascript
Is there something wrong with the index.js file?
package.json for cloudmersive says main is src/client.invoker/index.js but the file is not in that directory.
To use the library locally without publishing to a remote npm registry, first install the dependencies by changing
into the directory containing package.json. Let’s call this JAVASCRIPT_CLIENT_DIR. Then run:
npm install
Next, link it globally in npm with the following, also from JAVASCRIPT_CLIENT_DIR:
npm link
Finally, switch to the directory you want to use your cloudmersive from, and run:
npm link /path/to/<JAVASCRIPT_CLIENT_DIR>
You should now be able to require('cloudmersive') in javascript files from the directory you ran the last
command above from.
You can checkout the README.md file inside the cloudmersive module which you have installed inside your node_modules directory to get more detailed instructions on this.
Related
I am running through the Hello World app tutorial in GCP. And I am getting stuck at the server.js step.
The code of the server.js is as below:
'use strict';
const mongodb = require('mongodb');
const http = require('http');
const nconf = require('nconf');
let uri = 'mongodb+srv://my_name:<mypassword>#mydatabase-clr75.gcp.mongodb.net/test?retryWrites=true&w=majority';
if (nconf.get('mongoDatabase')) {
uri = `${uri}/${nconf.get('mongoDatabase')}`;
}
console.log(uri);
mongodb.MongoClient.connect(uri, (err, db) => {
if (err) {
throw err;
}
// Create a simple little server.
http.createServer((req, res) => {
if (req.url === '/_ah/health') {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.write('OK');
res.end();
return;
}
const collection = db.collection('Messages');
var datetime = new Date();
const msg = {
msgDescription: '\nHello World received on ' + datetime
};
collection.insert(msg, (err) => {
if (err) {
throw err;
}
// push out a range
let msglist = '';
collection.find().toArray((err, data) => {
if (err) {
throw err;
}
data.forEach((msg) => {
msglist += `${msg.msgDescription}; `;
});
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.write('Messages received so far:\n');
res.end(msglist);
});
});
}).listen(process.env.PORT || 8080, () => {
console.log('started web process');
});
});
I receive the error as below:
mongodb+srv://my_name:#mydatabase-clr75.gcp.mongodb.net/test?retryWrites=true&w=majority
/home/herboratory/node_modules/mongodb/lib/url_parser.js:19
throw new Error('invalid schema, expected mongodb');
^ Error: invalid schema, expected mongodb
at module.exports (/home/herboratory/node_modules/mongodb/lib/url_parser.js:19:11)
at connect (/home/herboratory/node_modules/mongodb/lib/mongo_client.js:486:16)
at Function.MongoClient.connect (/home/herboratory/node_modules/mongodb/lib/mongo_client.js:250:3)
at Object. (/home/herboratory/server.js:12:21)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Function.Module.runMain (module.js:694:10) npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! test#1.0.0 start: node
server.js npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the
test#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!
/home/herboratory/.npm/_logs/2019-06-26T03_58_26_823Z-debug.log
I was wondering it should be the format error after reading some other posts here with the same error line, so I've tried '...', "..." and without any quotation mark but still remain error. Would please guide me where's the error?
Except for the URI, is there anywhere else I also need to modify inside the code? As far as I know from the instruction I just need to insert my own Atlas Connection string.
Many thanks.
The error invalid schema, expected mongodb means that you're using an outdated node driver version. The old driver cannot parse the new mongodb+srv URI scheme.
Support for the mongodb+srv scheme was added in the node driver version 3.0 in this ticket: NODE-1145.
Upgrade your node driver using:
$ npm install mongodb
and the error should go away.
I had the same error. The problem was with setup in mongoDB Atlas and setup in my Application.
In mongoDB Atlas:
Create DATABASE and COLLECTION
Create Database User
Add your IP Address (public) in IP Whitelist, Network Access
Example of my solution:
File .env
MONGO_URI=mongodb+srv://jmendoza:your-password#cluster0-7rxkw.mongodb.net/nodeapi?retryWrites=true&w=majority
PORT=3000
File app.js
const express = require('express');
const morgan = require('morgan');
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');
const { postRoutes } = require('./routes/posts');
const app = express();
const port = process.env.PORT || 3000;
dotenv.config();
// BD
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('mongoDB, Atlas. Connected'))
.catch((err) => console.error(err));
// Middleware
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(expressValidator());
// Routes
app.use('/api/v1', postRoutes);
app.listen(port, () => {
console.log(`A NodeJS API is listining on port: ${port}`);
});
File package.json
{
"name": "node-api",
"version": "1.0.0",
"description": "A NodeJS API",
"main": "app.js",
"scripts": {
"dev": "nodemon app.js"
},
"keywords": [
"node",
"api"
],
"author": "Jonathan Mendoza",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-validator": "^5.3.1",
"mongoose": "^5.9.7",
"morgan": "^1.9.1",
"nodemon": "^2.0.3"
}
}
Running application (console)
jmendoza#jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Basic-Node-API$ npm run dev
> node-api#1.0.0 dev /home/jmendoza/IdeaProjects/NodeJS-API-Course/Basic-Node-API
> nodemon app.js
[nodemon] 2.0.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
A NodeJS API is listining on port: 3000
mongoDB, Atlas. Connected
NodeJS Version
jmendoza#jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Basic-Node-API$ node -v
v13.12.0
You can see my full code on GitHub:
https://github.com/JonathanM2ndoza/NodeJS-API-Course/tree/master/Basic-Node-API
here iam using a cloud functions to create users i am using a express module when i try to deploy this code it deploying to cloud funtions with message that Error : Funtions did not deploy properly
const express = require('express');
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const serviceaccount = require('./ServiceAccountKey.json');
const app = express();
admin.initializeApp({
credential: admin.credential.cert(serviceaccount)
});
app.post('/',(req,res)=>{
if(req.method!== 'POST'){
res.status(400).send("what are u trying baby");
return;
}
admin.auth().createUser({
email:req.body.email,
password: req.body.pass,
}).then(function(userRecord){
res.send({'uid': userRecord.uid});
return;
}).catch(function(error){
res.send({'error': 'Try COrrect one baby'});
return;
});
return;
});
exports.register = funtions.Https.onRequest(app);
when i add this at end
module.exports = {
app
}
it showing funtion deployed but its not showing in cloud functions dashboard
what wrong am i doing here
here is the error what ima getting i cnat get whAT THE error is
⚠ functions[register(us-central1)]: Deployment error.
Function failed on loading user code. Error message: Code in file index.js can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'express'
at Function.Module._resolveFilename (module.js:476:15)
at Function.Module._load (module.js:424:25)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/user_code/index.js:1:79)
at Module._compile (module.js:577:32)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
Functions deploy had errors with the following functions:
register
You code never uses the firebase-functions modules to declare a Cloud Function. Your functions variable is going unused. You can't just export any function an expect it to run - it has to be built by the SDK.
If you have an express app to deploy, you need to export it via an HTTP type function:
exports.app = functions.https.onRequest(app);
First, I think you need to change the endpoint of the url. Don't just put '/'. Maybe like '/user/create'.
app.post('/user/create',(req,res)=>{
if(req.method!== 'POST'){
res.status(400).send("what are u trying baby");
return;
}
admin.auth().createUser({
email:req.body.email,
password: req.body.pass,
}).then(function(userRecord){
res.send({'uid': userRecord.uid});
return;
}).catch(function(error){
res.send({'error': 'Try COrrect one baby'});
return;
});
return;
});
exports.register = funtions.Https.onRequest(app);
And in your firebase.json you should rewrite the url :
{
"functions": {
...
},
"hosting": {
"public": "public",
"rewrites": [
{
"source": "/user/create",
"function": "register"
}
]
}
}
For more explanation, you can follow this tutorial.
I got a SailsJS application in which I need to reference a htpasswd file that is located at the root of my project:
var auth = require('http-auth');
var basic = auth.basic({
authRealm: "Admin Panel",
authFile: 'htpasswd', // <-- how do I specify the path to this file ?
authType: 'basic'
});
module.exports = function(req, res, next) {
basic.apply(req, res, function(username) {
if(!username) {
return res.serverError(403, 'You are not authorized');
}
next();
})(req, res);
}
I have tried using:
authFile: '/htpasswd'
As well as:
authFile: '~/htpasswd'
Neither works.
Update
Hurmm....it seems like it's not the code that has error, somehow, my Sailsjs application can't find the htpasswd module.
I did do:
sudo npm install -g htpasswd
I also used htpasswd command line to generate the htpasswd file...somethings wrong with my project setup...
My console error says:
Error: Cannot find module 'htpasswd'
at Function.Module._resolveFilename (module.js:336:15)
at Function.Module._load (module.js:278:25)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/Users/MacUser/SailsProjects/SecurePanel/node_modules/http-auth/gensrc/auth/basic.js:11:14)
Use the native __dirname variable which evaluates to the path of the current file.
See what it is using console.log(__dirname). And then you could do:
var basic = auth.basic({
realm: "Admin Panel",
file: __dirname + "/path_from_current_file_to/htpasswd"
});
So if the root was a folder up from this the folder that this script is in, you could do
__dirname + "/../htpasswd"
I am trying to define some endpoints and do a test using nodejs. In server.js I have:
var express = require('express');
var func1 = require('./func1.js');
var port = 8080;
var server = express();
server.configure(function(){
server.use(express.bodyParser());
});
server.post('/testend/', func1.testend);
and in func1.js:
var testend = function(req, res) {
serialPort.write("1", function(err, results) {
serialPort.write("2" + "\n", function(err, results) {
});
});
});
exports.testend = testend;
Now in test.js I am trying to use this endpoint:
var should = require('should');
var assert = require('assert');
var request = require('supertest');
var http = require('http');
var app = require('./../server.js');
var port = 8080;
describe('Account', function() {
var url = "http://localhost:" + port.toString();
it('test starts', function(done) {
request(url).post('/testend/')
// end handles the response
.end(function(err, res) {
if (err) {
throw err;
}
res.body.error.should.type('string');
done();
});
});
});
But when I run node test.js I am getting this error:
describe('Account', function() {
^
ReferenceError: describe is not defined
at Object. (/test/test.js:9:1)
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:906:3
How can I fix the issue?
Assuming you are testing via mocha, you have to run your tests using the mocha command instead of the node executable.
So if you haven't already, make sure you do npm install mocha -g. Then just run mocha in your project's root directory.
if you are using vscode, want to debug your files
I used tdd before, it throw ReferenceError: describe is not defined
But, when I use bdd, it works!
waste half day to solve it....
{
"type": "node",
"request": "launch",
"name": "Mocha Tests",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"-u",
"bdd",// set to bdd, not tdd
"--timeout",
"999999",
"--colors",
"${workspaceFolder}/test/**/*.js"
],
"internalConsoleOptions": "openOnSessionStart"
},
To run tests with node/npm without installing Mocha globally, you can do this:
• Install Mocha locally to your project (npm install mocha --save-dev)
• Optionally install an assertion library (npm install chai --save-dev)
• In your package.json, add a section for scripts and target the mocha binary
"scripts": {
"test": "node ./node_modules/mocha/bin/mocha"
}
• Put your spec files in a directory named /test in your root directory
• In your spec files, import the assertion library
var expect = require('chai').expect;
• You don't need to import mocha, run mocha.setup, or call mocha.run()
• Then run the script from your project root:
npm test
You can also do like this:
var mocha = require('mocha')
var describe = mocha.describe
var it = mocha.it
var assert = require('chai').assert
describe('#indexOf()', function() {
it('should return -1 when not present', function() {
assert.equal([1,2,3].indexOf(4), -1)
})
})
Reference: http://mochajs.org/#require
i have this error when using "--ui tdd".
remove this or using "--ui bdd" fix problem.
OP asked about running from node not from mocha. This is a very common use case, see Using Mocha Programatically
This is what injected describe and it into my tests.
mocha.ui('bdd').run(function (failures) {
process.on('exit', function () {
process.exit(failures);
});
});
I tried tdd like in the docs, but that didn't work, bdd worked though.
for Jest you have to add "jest": true to .eslintrc
{
"env": {
"browser": true,
"es6": true,
"jest": true
},
...
Make sure you have a folder named as test that contains your test.js file.
Also make sure you have mocha available in your project by running mocha -version in terminal (at project path)
Make sure your project has package.json available, if not run npm init -y
And finally to run mocha test scripts, on terminal (on project path) run npm test
I am trying to setup my Nodejs/Express hosting server to have multiple applications (Sails.js app type) running on my VPS but I got this error :
/srv/data/web/vhosts/default/node_modules/vhost/index.js:78
throw new TypeError('argument server is unsupported')
^
TypeError: argument server is unsupported
at createHandle (/srv/data/web/vhosts/default/node_modules/vhost/index.js:78:9)
at vhost (/srv/data/web/vhosts/default/node_modules/vhost/index.js:39:16)
at Object.<anonymous> (/srv/data/web/vhosts/default/server.js:46:9)
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:906:3
Of course I previously installed all my dependencies.
My Nodejs/Express base configuration for multiple apps is good because it works fine with this express vhosts example configuration:
https://github.com/loicsaintroch/express-vhosts
So here my nodejs server app structure:
.../vhosts/default/server.js
package.json
/app1
/app.js
/app2
/app.js
/app3
/app.js
And here my server.js file based on this previous github example:
// Module dependencies
var express = require('express');
var vhost = require('vhost');
var app = express();
// vhosts
app
.use(vhost('app1.com', require('./app1/app.js')))
.listen(8080);
And the package.json file:
{
"name": "default",
"private": true,
"version": "0.0.1",
"description": "Default git repository for some web applications.",
"dependencies": {
"express": "^4.2.0",
"vhost": "^2.0.0",
"forever": "^0.11.1",
"static-favicon": "^1.0.0",
"ejs": "^1.0.0",
"morgan": "^1.0.0",
"cookie-parser": "^1.0.1",
"body-parser": "^1.0.0",
"debug": "^0.7.4"
},
"scripts": {
"start": "forever start server.js --prod",
"debug": "node debug server.js"
},
"main": "server.js"
}
Error come from vhost npm package:
/**
* Create handle to server.
*
* #param {function|Server} server
* #return {function}
* #api private
*/
function createHandle(server){
if (typeof server === 'function') {
// callable servers are the handle
return server
} else if (typeof server.emit === 'function') {
// emit request event on server
return function handle(req, res) {
server.emit('request', req, res)
}
}
throw new TypeError('argument server is unsupported')
}
OK here precisely I think vhost package has a problem with the app.js response from sails.js framework. Here the app.js file content from my Sails.js app:
/**
* app.js
*
* Use `app.js` to run your app without `sails lift`.
* To start the server, run: `node app.js`.
*
* This is handy in situations where the sails CLI is not relevant or useful.
*
* For example:
* => `node app.js`
* => `forever start app.js`
* => `node debug app.js`
* => `modulus deploy`
* => `heroku scale`
*
*
* The same command-line arguments are supported, e.g.:
* `node app.js --silent --port=80 --prod`
*/
// Ensure a "sails" can be located:
(function() {
var sails;
try {
sails = require('sails');
} catch (e) {
console.error('To run an app using `node app.js`, you usually need to have a version of `sails` installed in the same directory as your app.');
console.error('To do that, run `npm install sails`');
console.error('');
console.error('Alternatively, if you have sails installed globally (i.e. you did `npm install -g sails`), you can use `sails lift`.');
console.error('When you run `sails lift`, your app will still use a local `./node_modules/sails` dependency if it exists,');
console.error('but if it doesn\'t, the app will run with the global sails instead!');
return;
}
// Try to get `rc` dependency
var rc;
try {
rc = require('rc');
} catch (e0) {
try {
rc = require('sails/node_modules/rc');
} catch (e1) {
console.error('Could not find dependency: `rc`.');
console.error('Your `.sailsrc` file(s) will be ignored.');
console.error('To resolve this, run:');
console.error('npm install rc --save');
rc = function () { return {}; };
}
}
// Start server
sails.lift(rc('sails'));
})();
==============================================
UPDATE: FULL SOLUTION EXAMPLE
As a synthesis of the great answer I wrote a complete case study available here
https://github.com/migswd/express-sails-vhosts
==============================================
The problem here is that you're trying to shoehorn an example meant for Express apps to work with Sails apps.
If you look at the app.js files from the example vhost apps, they all use module.exports to return an Express app instance. The app.js from the Sails app you posted clearly does no such thing; it doesn't export anything at all. Furthermore, that file is calling sails.lift, which starts its own server listening on port 1337.
A little elbow grease can get this to work. Instead of lifting the Sails app, you can use sails.load which does everything except start listening on a port. This is an asynchronous method, so it'll require a reworking of your server.js as well.
The Sails app.js files become:
var sails = require('sails');
module.exports = function(cb) {
process.chdir(__dirname);
sails.load(cb);
};
Every running sails instance exposes its underlying Express app as .hooks.http.app, so in your server.js, use async or something similar to load all of the Sails apps, then hook them up with vhost:
// Module dependencies
var express = require('express');
var vhost = require('vhost');
var app = express();
var async = require('async');
async.auto({
app1: require('./app1/app.js'),
app2: require('./app2/app.js'),
app3: require('./app3/app.js')
}, function doneLoadingApps(err, apps) {
app
.use(vhost('app1.io', apps.app1.hooks.http.app))
.use(vhost('app2.io', apps.app2.hooks.http.app))
.use(vhost('app3.io', apps.app3.hooks.http.app))
// Mix in a vanilla Express app as well
.use(vhost('app4.io', require('./app4/app.js')))
.listen(8080);
});