I'm running into an issue where I try to require a .jpg image.
When Googling I thought it had something to do with Jest but now when I start from a clean project, not having Jest as a dependency I get the same error.
What can be the issue?
This is the files I'm trying to run
server.js
// Import express framework
const express = require('express')
// Import routes
const visionAiRouter = require('./routes/vision-ai-route')
// Setup default port
const PORT = process.env.PORT || 4000
// Create express app
const app = express()
// Vision AI Route
app.use('/ai', visionAiRouter)
// Implement route for errors
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
})
// Start express app
app.listen(PORT, function() {
console.log(`Server is running on: ${PORT}`)
})
vision-ai-route.js
// Import
const express = require('express')
const visionAi = require('../controllers/vision-ai-controller')
// Create express router
const router = express.Router()
router.get('/', visionAi.labelDetection)
// Export
module.exports = router
vision-ai-controller.js
// Assets
const cat = require('./../data/cat.jpg')
// Create controller for GET request to '/users/all'
exports.labelDetection = async (req, res) => {
// Imports the Google Cloud client library
const vision = require('#google-cloud/vision');
// Creates a client
const client = new vision.ImageAnnotatorClient();
// Performs label detection on the image file
const [result] = await client.labelDetection(cat);
const labels = result.labelAnnotations;
const stringify = JSON.stringify(labels);
await res.json(stringify)
}
package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "server.js",
"dependencies": {
"#google-cloud/vision": "^2.1.1",
"express": "^4.17.1",
"nodemon": "^2.0.4"
},
"devDependencies": {},
"scripts": {
"start": "nodemon server.js"
},
"author": "",
"license": "ISC"
}
Stacktrace
/Users/kod/Desktop/Code/Private/vision-ai/test/data/cat.jpg:1
����
^
SyntaxError: Invalid or unexpected token
at Module._compile (internal/modules/cjs/loader.js:721:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:690:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (/Users/kod/Desktop/Code/Private/vision-ai/test/controllers/vision-ai-controller.js:3:13)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
You can't require a non-code file as require is meant to load executable code. The correct equivalent would be const cat = fs.readFileSync('./test/data/cat.jpg').
Related
I have the following configuration js file
const firebase = require('firebase')
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "blahblahblah",
authDomain: "ivrs-fjj.firebaseapp.com",
databaseURL: "https://ivrs-fjj.firebaseio.com",
projectId: "ivrs-fjj",
storageBucket: "ivrs-fjj.appspot.com",
messagingSenderId: "10387869293211",
appId: "1:1038786929211:web:6ed1a5djf9855105ef21e",
measurementId: "G-ZTY9VS9GV9"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.database();
module.exports = {db}
Then in my app.js I have the following:
const express = require('express')
const app = express()
const port = 3000
const {db} = require('./config/firebaseConfiguration.js');
....
app.get('', (req, res) => {
// Display the db
console.log(db)
res.render('index')
})
app.listen(port, () => console.info(`Listening on port ${port}`))
Lastly, my package.json file is as follows:
{
"name": "Market",
"version": "1.0.0",
"description": "Marketplace",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon app.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^3.1.6",
"express": "^4.17.1",
"firebase": "^9.6.1"
},
"devDependencies": {
"nodemon": "^2.0.15"
}
}
and the folder structure I am using is as follows:
Market
---config
-------firebaseConfig.js
---node_modules
---views
---public
---app.js
---package.json
I get following error when I start the express server:
internal/modules/cjs/loader.js:438
throw e;
^
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in /Users/Documents/Market/node_modules/firebase/package.json
at throwExportsNotFound (internal/modules/esm/resolve.js:290:9)
at packageExportsResolve (internal/modules/esm/resolve.js:513:3)
at resolveExports (internal/modules/cjs/loader.js:432:36)
at Function.Module._findPath (internal/modules/cjs/loader.js:472:31)
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:867:27)
at Function.Module._load (internal/modules/cjs/loader.js:725:27)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object. (/Users/Documents/Market/config/firebaseConfiguration.js:3:18)
at Module._compile (internal/modules/cjs/loader.js:1063:30) {
code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
}
Does anyone know what I'm doing wrong and how I can fix this?!
Try export default db instead of export {db} or if you want to use the latter you can import it like this
const {db} = require('./config/firebaseConfiguration.js');
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
This problem has probably been posted about a dozen times, but I can't find a single fix to my problem.
Here is my code:
//////////////////// VARIABLES ////////////////////
//use express
var express = require('express');
//variable to use express
var app = express();
//use the body-parser middleware to handle post data
var bodyParser = require('body-parser');
//create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });
//create a variable for the server
//var server = require('http').Server(app)//
//////////////////// SETUP ////////////////////
//tells express to use ejs as the view/template engine
app.set('view engine', 'ejs');
//use express as middleware to serve static pages
app.use('/CSS', express.static('CSS'));
app.use('/images', express.static('images'));
//////////////////// FUNCTIONALITY ////////////////////
//sets index as the default page
app.get('/', function (req, res) {
res.render('index');
});
//serve specified pages
app.get('/:page', function (req, res) {
res.render(req.params.page);
});
app.post('/custom_rec', urlencodedParser, function (req, res) {
console.log(req.body);
res.render('custom_rec', {data: req.body});
});
const host = '0.0.0.0';
const port = process.env.PORT || 5000;
app.listen(port, host, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
Here are the relevant logs:
2018-10-23T08:42:25.388218+00:00 heroku[web.1]: State changed from crashed to starting
2018-10-23T08:42:30.109913+00:00 heroku[web.1]: Starting process with command `node ./index.js`
2018-10-23T08:42:33.503841+00:00 heroku[web.1]: Process exited with status 1
2018-10-23T08:42:33.525464+00:00 heroku[web.1]: State changed from starting to crashed
2018-10-23T08:42:33.439948+00:00 app[web.1]: module.js:549
2018-10-23T08:42:33.439965+00:00 app[web.1]: throw err;
2018-10-23T08:42:33.439967+00:00 app[web.1]: ^
2018-10-23T08:42:33.439968+00:00 app[web.1]:
2018-10-23T08:42:33.439970+00:00 app[web.1]: Error: Cannot find module '/app/index.js'
2018-10-23T08:42:33.439972+00:00 app[web.1]: at Function.Module._resolveFilename (module.js:547:15)
2018-10-23T08:42:33.439973+00:00 app[web.1]: at Function.Module._load (module.js:474:25)
2018-10-23T08:42:33.439975+00:00 app[web.1]: at Function.Module.runMain (module.js:693:10)
2018-10-23T08:42:33.439976+00:00 app[web.1]: at startup (bootstrap_node.js:191:16)
2018-10-23T08:42:33.439978+00:00 app[web.1]: at bootstrap_node.js:612:3
Here is my Procfile:
web: node ./index.js
Here is my package.json:
{
"name": "anirec",
"version": "1.0.0",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "hidden"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "hidden"
},
"homepage": "hidden",
"description": "",
"dependencies": {
"body-parser": "^1.18.3",
"ejs": "^2.6.1",
"express": "^4.16.4"
},
"engines": {
"node": "8.11.4"
}
}
Here is an image of my directory:
The app works using local host.
I've tried having my server listen to 'process.env.PORT'. I've tried taking out "main" in my package.json. I've tried a relative path in my Procfile. I've tried reinstalling node_modules. My Procfile is in the same directory as index.js.
What else am I missing? Thanks in advance.
Edit: I've also tried restarting the server/dyno. 'Index.js' is also listed when I type 'git ls-files' into my terminal.
You have case-sensitive issue, your Index.js starts with capital letter, it should be index.js instead.
I have a simple webpack with react hotloader & express setup and working. I'm trying to add an external node module that will register a sub router for some services. For some reason, doing so causes a strange exception (see below).
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config');
var app = express();
var router = express.Router();
var mod = require("my-module");
mod.registerServices(router); // <-- adds routes to the router
app.use("/api/v1*", router); // <-- This line causes the error
var compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
stats: {
colors: true
}
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(3000, 'localhost', function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://localhost:3000');
});
The Exception:
$ node server.js
/Users/bmonro/Documents/Code/nui-redux/node_modules/react-transform-hmr/lib/index.js:51
throw new Error('locals[0] does not appear to be a `module` object with Hot Module ' + 'replacement API enabled. You should disable react-transform-hmr in ' + 'production by using `env` section in Babel configuration. See the ' + 'example in README: https://github.com/gaearon/react-transform-hmr');
^
Error: locals[0] does not appear to be a `module` object with Hot Module replacement API enabled. You should disable react-transform-hmr in production by using `env` section in Babel configuration. See the example in README: https://github.com/gaearon/react-transform-hmr
at Object.proxyReactComponents [as default] (/Users/bmonro/Documents/Code/nui-redux/node_modules/react-transform-hmr/lib/index.js:51:11)
at Object.<anonymous> (/Users/bmonro/Documents/Code/nui-redux/src/ext/nui-company-admin/lib/CompanyLocation/components/simple.js:25:60)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
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/bmonro/Documents/Code/nui-redux/src/ext/nui-company-admin/lib/CompanyLocation/containers/CompanyLocationPage.js:13:25)
at Module._compile (module.js:434:26)
UPDATE
Turns out that removing this from .babelrc where I have some react transforms enabled and subsequently removing all of the web pack hotloader plugins & middleware gets the router working again.
{
"transform": "react-transform-hmr",
"imports": ["react"],
"locals": ["module"]
}
Try this solution: don't use babel-plugin-react-transform in .babelrc, use config in webpack.config.js
module: {
loaders: [
{
test: /\.(js|jsx)$/,
loader: 'babel',
include: path.join(__dirname, 'src'),
query: {
plugins: [
["react-transform", {
transforms: [{
transform: "react-transform-hmr",
imports: ["react"],
locals: ["module"]
}]
}]
]
}
}
]
}
Details:
https://github.com/gaearon/babel-plugin-react-transform/issues/62
https://github.com/gaearon/react-transform-hmr/issues/5
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);
});