io.on('connection', socket =>{
^
TypeError: io.on is not a function
at Object. (D:\shalini course\projects\chat app\nodeserver\nodeapp.js:7:4)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Module._load (node:internal/modules/cjs/loader:922:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
it shows this error when I run a cmd - node nodeapp.js
please do reply If any idea how to fix it?
enter image description here
I tried running an application of socket.io on 5000 port using node.js but it's not working.
you have to add the socket io server to the http server, the mistake you are doing is that you are adding the socket io server to nowhere, to the aire, try with this before to iniltialize the server on port 5000
//CREATE THE SERVER NODE JS
const server = http.createServer(app)
// CREATE SOCKET.IO SERVER CONNECT WITH OUR SERVER
const io = new Server(server);
HERE PUT YOUR SOCKET IO CODE, io.on,.....
server.listen(port,()=>{
console.log(`listening on port ${port}`)
});
Yes, "io" that you are trying to use a method on is not a function on that class
in your code "io" includes the whole package of socketio all the classes and functions
"io" in your code has all the classes that your can use by
const myClass = new io.(someclass)()
You can impove your code like this
const socketiopackage = require('socket.io')
const port = 5000
const io = new socketiopackage.Server(5000,{cors: {"Access-Control-Allow-Origin": "*",methods: ["GET", "POST", "OPTIONS"]},})
var users = {}
io.on('connection',socket=>{
socket.on('new-user-joined',name=>{
users[socket.id]=name
socket.broadcast.emit('user-joined',name)
})
socket.on('send',message=>{
socket.broadcast.emit('recieve',{message,name:user[socket.id]})
})
})
or it is easier to directly import your required class
const { Server } = require('socket.io')
const port = 5000
const io = new Server(5000,{cors: {"Access-Control-Allow-Origin": "*",methods: ["GET", "POST", "OPTIONS"]},})
var users = {}
io.on('connection',socket=>{
socket.on('new-user-joined',name=>{
users[socket.id]=name
socket.broadcast.emit('user-joined',name)
})
socket.on('send',message=>{
socket.broadcast.emit('recieve',{message,name:user[socket.id]})
})
})
I have added some cors settings in the options for creating a server, it is a good practice to do so
Using Nodemon
install it using
npm install -g nodemon
then use it using
nodemon (fileName).js
I forked a Discord music bot from GitHub to ReplIt and then I try to follow steps to run the bot successfully!
I use Node.JS v.14!
When I run the bot I receive following error:
/home/runner/A-Advance-Discord-Music-Bot-Like-Hydra-/node_modules/bindings/bindings.js:121
throw e;
^
Error: The module '/home/runner/A-Advance-Discord-Music-Bot-Like-Hydra-/node_modules/better-sqlite3/build/Release/better_sqlite3.node'
was compiled against a different Node.js version using
NODE_MODULE_VERSION 72. This version of Node.js requires
NODE_MODULE_VERSION 88. Please try re-compiling or re-installing
the module (for instance, using `npm rebuild` or `npm install`).
at Object.Module._extensions..node (node:internal/modules/cjs/loader:1151:18)
at Module.load (node:internal/modules/cjs/loader:972:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Module.require (node:internal/modules/cjs/loader:996:19)
at require (node:internal/modules/cjs/helpers:92:18)
at bindings (/home/runner/A-Advance-Discord-Music-Bot-Like-Hydra-/node_modules/bindings/bindings.js:112:48)
at Object.<anonymous> (/home/runner/A-Advance-Discord-Music-Bot-Like-Hydra-/node_modules/better-sqlite3/lib/database.js:9:24)
at Module._compile (node:internal/modules/cjs/loader:1092:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10)
at Module.load (node:internal/modules/cjs/loader:972:32) {
code: 'ERR_DLOPEN_FAILED'
}
exit status 1
And here is my index.js file:
//Importing all needed Commands
const Discord = require("discord.js"); //this is the official discord.js wrapper for the Discord Api, which we use!
const colors = require("colors"); //this Package is used, to change the colors of our Console! (optional and doesnt effect performance)
const Enmap = require("enmap"); //this package is our Database! We will use it to save the data for ever!
const fs = require("fs"); //this package is for reading files and getting their inputs
//Creating the Discord.js Client for This Bot with some default settings ;) and with partials, so you can fetch OLD messages
const client = new Discord.Client({
fetchAllMembers: false,
restTimeOffset: 0,
shards: "auto",
restWsBridgetimeout: 100,
disableEveryone: true,
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
intents: ["GUILDS", "GUILD_MESSAGES"]
});
require('events').EventEmitter.defaultMaxListeners = 100;
process.setMaxListeners(100);
//Loading files, with the client variable like Command Handler, Event Handler, ...
["clientvariables", "command", "events", "erelahandler", "requestreacts"].forEach(handler => {
require(`./handlers/${handler}`)(client);
});
//Each Database gets a own file and folder which is pretty handy!
client.premium = new Enmap({ name: "premium", dataDir: "./databases/premium" })
client.stats = new Enmap({ name: "stats", dataDir: "./databases/stats" })
client.settings = new Enmap({ name: "setups", dataDir: "./databases/settings" })
client.setups = new Enmap({ name: "setups", dataDir: "./databases/setups" })
client.queuesaves = new Enmap({ name: "queuesaves", dataDir: "./databases/queuesaves", ensureProps: false})
client.modActions = new Enmap({ name: 'actions', dataDir: "./databases/warns" });
client.userProfiles = new Enmap({ name: 'userProfiles', dataDir: "./databases/warns" });
//login into the bot
client.login(require("./botconfig/config.json").token);
Can anyone tell me my problem?
Sorry for my bad English
You would have to force clean your npm cache and remove your node_modules and reinstall them again to compile them against a new node version, for the same you may use the following commands in your Console / Shell:
rm -rf node_modules && rm package-lock.json && npm cache clear --force && npm cache clean --force && npm install
Seems you updated the Node.js version, you can use npm rebuild to rebuild to the new version of Node.js then start the application, use only once the command not every time you start the applicatoin
To fix this error we need to completely repair our npm memory!
In the first step, we need to delete node_modules:
$ rm -rf node_modules package-lock.json
And then clean up our npm memory:
$ npm cache clear --force
$ npm cache clean --force
And reinstall it so that it compiles in the new version!
npm install
I think this can be helpful!
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
I created a simple react app with serverside rendering using this workshop git as a base with my minor changes.
So when I run locally NODE_ENV=server node server.js it works fine. But my attempts to deploy this app on a trial of Bluemix the Nodejs server failed. Here's a log :
Here is my server.js code:
require('babel-register')
const express = require('express')
const React = require('react')
const ReactDOMServer = require('react-dom/server')
const ReactRouter = require('react-router')
const StaticRouter = ReactRouter.StaticRouter
const _ = require('lodash')
const fs = require('fs')
const PORT = 5050
const baseTemplate = fs.readFileSync('./index.html')
const template = _.template(baseTemplate)
const App = require('./js/App').default
const server = express()
server.use('/_public', express.static('./_public'))
server.use((req, res) => {
const context = {}
const body = ReactDOMServer.renderToString(
React.createElement(StaticRouter, {location: req.url,
context: context},
React.createElement(App))
)
res.write(template({body: body}))
res.end()
})
console.log('listening on port', PORT)
server.listen(PORT)
P.S. It's obvious that it doesn't understand ES6 syntax in js/App.js, but on my local server it works.
By default NODE_ENV=production but according to Bluemix docs I created a file in .profile.d directory
node_env.sh code:
export NODE_ENV=server;
But I'm not sure if this file changes node_env.
I'm hoping someone more knowledgeable than me can offer a better solution, but here is what I did to make your app work. There is probably a better answer.
Assuming that you do NOT want to run in production mode...
1) server.js: Listen to the port as set in the PORT env var.
server.listen(process.env.PORT || PORT)
2) package.json: Add start command in scripts
"start": "babel-node server.js --presets es2015,stage-2"
3) Get babel-cli
npm install --save-dev babel-cli
npm install --save-dev babel-preset-es2015 babel-preset-stage-2
4) Create a manifest.yml to set CF properties
applications:
- name: rvennam-node-react
memory: 1G
disk_quota: 2G
env:
NPM_CONFIG_PRODUCTION: false
NODE_ENV: dev
5) remove eslint dependencies from devDependencies in package.json (there was a mismatch)
Again, this is assuming you want to run on Bluemix under dev mode. If you wanted production on Bluemix, I would think you would want to use webpack to build locally, and then push and serve your dist directory.