Node Server Ports keep getting 'Plugged Up' during development - javascript

I'm over a month into development of a MEVN app with MySQL. I'm using a framework called MEVN-CLI but that shouldn't really matter.
I keep having to change my server port ever few days whenever I get this error:
[nodemon] 2.0.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,html,css,json,md
[nodemon] starting `node run server.js --port 9000/api --open`
events.js:288
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::3000
at Server.setupListenHandle [as _listen2] (net.js:1309:16)
at listenInCluster (net.js:1357:12)
at Server.listen (net.js:1445:7)
at Function.listen (C:\Dev\Projects\node-mysql\server\node_modules\express\lib\application.js:618:24)
at Object.<anonymous> (C:\Dev\Projects\node-mysql\server\server.js:258:5)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
Emitted 'error' event on Server instance at:
at emitErrorNT (net.js:1336:8)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'EADDRINUSE',
errno: 'EADDRINUSE',
syscall: 'listen',
address: '::',
port: 3000
}
I change between 9000, 3000, 3002, 8000, etc. I want to keep it on a single port but this keeps happening and I can't find what's causing it.
I have a client and a server, they communicate with Axios, my Server communicates with a MySQL server I host elsewhere but I also think this is irrelevant but I figure it can't hurt to share that.
Here is my server:
const port = process.env.PORT || 4000;
const env = require("./env.json");
const express = require("express");
const mysql = require("mysql");
const path = require("path");
const bodyParser = require("body-parser");
const favicon = require("serve-favicon");
const app = express();
const cors = require("cors");
const {
testColumns,
showUsers,
searchResultColumns,
showAccountColumns
} = require("./mysql/columns");
app.use(bodyParser.json());
app.use(favicon(path.join(__dirname, "public", "favicon.ico")));
app.use(cors());
//* Build MySQL Connection
const db = mysql.createConnection({
host: env.server,
user: env.user,
password: env.pass,
database: env.schema
});
//* Connect to Database
db.connect((err) => {
if (err) {
console.log("Error Connecting:", err);
}
console.log("MySQL Connected...");
});
app.get(`/api/v1/:query/:x`, (req, res) => {
[Business Logic - Works fine]
if (err) {
// If error
console.log(err);
}
// If no results
else if (results == 0) {
res.send(`No Results\n ${results} \n - ${err}`);
return;
}
// If successful
res.send(results);
});
});
app.get(`/api/v1/:query/`, (req, res) => {
[Business Logic - Works fine]
if (err) {
// If error
console.log(err);
}
// If no results
else if (results == 0) {
res.send(`No Results\n ${results} \n - ${err}`);
return;
}
// If successful
res.send(results);
});
});
//* Root Handler
app.get("/", (req, res) =>
res.sendFile(path.join(__dirname + "/public/index.html"))
);
//? Error Handler
app.get("/404", (req, res) =>
res.sendFile(path.join(__dirname + "/public/404.html"))
);
//! Error Handler
app.get("/sample", (req, res) =>
res.sendFile(path.join(__dirname + "/public/sample.html"))
);
//? Listen for server port
app.listen(port, () => {
console.log(`Sample Dev Server at:${port}`);
});
I deleted some stuff that's not really relevant because it was hundreds of similar lines, I haven't abstracted my routing away yet.
This is my router:
import Vue from "vue";
import Router from "vue-router";
import Home from "./views/Home.vue";
import NotFound from "./views/NotFound.vue";
Vue.use(Router);
export default new Router({
mode: "history",
base: process.env.BASE_URL,
routes: [
{
path: "/",
name: "Home",
component: Home
},
{
path: "/NotFound",
name: NotFound,
component: () => import("./views/NotFound.vue")
},
{
path: "/search",
component: searchPage,
children: [
{ path: "/search/byName", component: searchByName },
{ path: "/search/china", component: searchByNumber }
]
}
]
});
And if it's relevant, this is my packages.json file:
{
"name": "vmax",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.19.2",
"core-js": "^3.6.4",
"vue": "^2.6.11",
"vue-router": "^3.1.6",
"vuetify": "^2.2.11"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.3.0",
"#vue/cli-plugin-eslint": "~4.3.0",
"#vue/cli-service": "~4.3.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^6.2.2",
"sass": "^1.19.0",
"sass-loader": "^8.0.0",
"vue-cli-plugin-vuetify": "~2.0.5",
"vue-template-compiler": "^2.6.11",
"vuetify-loader": "^1.3.0"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
I changed just now to port 4000 and it's working just find but something is wrong that's causing me to have to change server ports every few days.

Probably the PORT is in use.
To terminate program PORT,
$ killall -9 node

Node / Express: EADDRINUSE, Address already in use happens when closing VS Code, particularly on Windows when a server is running with WSL.
I'm currently using something called CurrPorts which is free to view which ports are in use, and force close them.
To be clear, it's not specific to Windows or WSL, but that is where it seems most prevalent. If you're in the habit of using port 3000, 5500, or 8080 for example - it's likely in use by Node.

Add this in your "package.json" file
"stop-win": "Taskkill /IM node.exe /F",
"stop-linux": "killall node"

Related

.pr[nodemon] app crashed - waiting for file changes before starting... While deploying NodeJS server on Heroku

I am facing
[nodemon] app crashed - waiting for file changes before starting...
While hosting my NodeJS Apollo GraphQL express server on Heroku.
It is also showing
2022-10-06T17:21:11.889722+00:00 app[web.1]: [nodemon] 2.0.20
2022-10-06T17:21:11.889912+00:00 app[web.1]: [nodemon] to restart at any time, enter `rs`
2022-10-06T17:21:11.890274+00:00 app[web.1]: [nodemon] watching path(s): *.*
2022-10-06T17:21:11.890314+00:00 app[web.1]: [nodemon] watching extensions: js,mjs,json
2022-10-06T17:21:11.890669+00:00 app[web.1]: [nodemon] starting `nodemon -r esm .`
2022-10-06T17:21:13.608667+00:00 app[web.1]: /app/node_modules/esm/esm.js:1
2022-10-06T17:21:13.616378+00:00 app[web.1]: const __global__ = this;(function (require, module, __shared__) { var __shared__;const
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
Here is my index.js
import express from "express";
import mongoose from "mongoose";
import { DB, mode } from "./config";
import { ApolloServer } from "apollo-server-express";
import AuthMiddleware from "./middlewares/auth";
import * as AppModels from "./models";
import { resolvers, typeDefs } from "./graphql";
const startServer = async () => {
const PORT = process.env.PORT || 3000;
try {
const app = express();
app.use(AuthMiddleware);
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
playground: mode,
context: ({ req }) => {
let { isAuth, user } = req;
return { req, isAuth, user, ...AppModels };
},
});
mongoose.connect(DB, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
await apolloServer.start();
await apolloServer.applyMiddleware({ app });
app.listen({ port: PORT }, () =>
console.log(`Server started at port ${PORT}`,)
);
} catch (err) {
console.log("error: "+err);
}
};
startServer();
Here is my package.json
{
"name": "forefest-backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon -r esm .",
"server": "sudo systemctl start mongod && nodemon -r esm",
"dev": "nodemon -r esm"
},
"repository": {
"type": "git",
"url": "git+https://github.com/anshuman-8/forefest-backend.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/anshuman-8/forefest-backend/issues"
},
"homepage": "https://github.com/anshuman-8/forefest-backend#readme",
"dependencies": {
"apollo-server-express": "^3.10.2",
"bcryptjs": "^2.4.3",
"consola": "^2.15.3",
"dotenv": "^16.0.2",
"esm": "^3.2.25",
"express": "^4.18.1",
"graphql": "^16.6.0",
"jsonwebtoken": "^8.5.1",
"lodash": "^4.17.21",
"mongoose": "^6.6.1",
"mongoose-paginate-v2": "^1.7.1",
"nodemon": "^2.0.20",
"yup": "^0.32.11"
}
}
I have tried multiple ways of fixing this problem, Please help me.
This is my first time deploying a server.

internal/modules/cjs/loader.js:905 throw err; ^ Error: Cannot find module 'cors'

When I run npm start
My result is ..
> nodefirebase_curd#1.0.0 start
> nodemon index.js
[nodemon] 2.0.13
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
internal/modules/cjs/loader.js:905
throw err;
^
Error: Cannot find module 'cors'
Require stack:
- C:\Users\tong1\Desktop\test-Firebase\nodeFirebase_CURD\index.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
at Function.Module._load (internal/modules/cjs/loader.js:746:27)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:92:18)
at Object.<anonymous> (C:\Users\tong1\Desktop\test-Firebase\nodeFirebase_CURD\index.js:3:14)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\\tong1\\Desktop\\test-Firebase\\nodeFirebase_CURD\\index.js'
]
}
What wrong with this. I try to fix cors function but it doesn't work.
'use strict';
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const config = require('./config');
const studentRoutes = require('./routes/student-routes');
const app = express()
app.use(express.json());
app.use(cors());
app.use(bodyParser.json());
app.use('./api', studentRoutes.routes);
app.listen(config.port, () => console.log('App is listening on url http://localhost:' + config.port));
This is my package.json.
{
"name": "nodefirebase_curd",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"firebase": "^9.1.0",
"firebase-admin": "^9.12.0"
},
"devDependencies": {
"nodemon": "^2.0.13"
}
}
I'm struck in this problem with a long time.
Can you help me, please.
Thank you so much.
you don't have cors in dependencies
Install the dependency by npm i cors -P

Syntax Error: Unexpected Token async()

I have been following this tutorial on using GraphQL and it has told me to write this block of code in my src/index.js file:
const express = require('express');
const bodyParser = require('body-parser');
const {graphqlExpress, graphiqlExpress} = require('apollo-server-express');
const schema = require('./schema');
// 1
const connectMongo = require('./mongo-connector');
// 2
const start = async () => {
// 3
const mongo = await connectMongo();
var app = express();
app.use('/graphql', bodyParser.json(), graphqlExpress({
context: {mongo}, // 4
schema
}));
app.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
}));
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Hackernews GraphQL server running on port ${PORT}.`)
});
};
// 5
start();
Though when I try to run the code using: node ./src/index.js it gives me this error:
const start = async () => {
^
SyntaxError: Unexpected token (
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
at startup (bootstrap_node.js:149:9)
I've searched online and it seems that if might be caused by the node.js version from here but I've checked my noed.js version and it's 8.3.0 so it should be supported without having to use Babel if I'm not mistaken.
Here is my package.json file:
{
"name": "graphql-js-tutorial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"apollo-server-express": "^1.1.2",
"body-parser": "^1.17.2",
"express": "^4.15.4",
"graphql": "^0.11.2",
"graphql-tools": "^1.2.2",
"mongodb": "^2.2.31"
}
}
async functions are only available since node 8.3
your code is equivalent to (without async/await)
const start = () => {
return connectMongo().then(mongo => {
var app = express();
app.use('/graphql', bodyParser.json(), graphqlExpress({
context: {mongo}, // 4
schema
}));
app.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
}));
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Hackernews GraphQL server running on port ${PORT}.`)
});
return;
});
};
start your app by the command node yourAppFile -harmony!
async function is available in the harmony mode under Node7.+

Simple API.AI node.js webhook crashes on Heroku

I try to get my feet wet implementing a simply webhook for Google's NLP API.AI interface. I want to use Heroku as the server using node.js. The problem is that I can build and deploy the code on Heroku but the execution fails immediately.
Extract from the build log (note that the "real name" app is not test, I just changed it for this post)
[...]
2017-07-21T13:28:57.000000+00:00 app[api]: Build succeeded
2017-07-21T13:29:07.012028+00:00 heroku[web.1]: Starting process with command `npm start`
2017-07-21T13:29:10.516218+00:00 app[web.1]:
2017-07-21T13:29:10.516234+00:00 app[web.1]: > test#0.0.3 start /app
2017-07-21T13:29:10.516235+00:00 app[web.1]: > node app.js
2017-07-21T13:29:10.516236+00:00 app[web.1]:
2017-07-21T13:29:11.076809+00:00 heroku[web.1]: State changed from starting to crashed
I have tried many different versions of code but even this code which is reduced to pretty much nothing fails to execute.
Here is my app.js:
'use strict';
process.env.DEBUG = 'actions-on-google:*';
const ApiAiApp = require('actions-on-google').ApiAiApp;
const test = function(request, response) {
// todo
};
module.exports = {
test
};
And this is the package.json file:
{
"name": "test",
"description": "virtual scrum master",
"version": "0.0.3",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"scripts": {
"lint": "semistandard --fix \"**/*.js\"",
"start": "node app.js",
"monitor": "nodemon app.js",
"deploy": "gcloud app deploy"
},
"engines": {
"node": "6.11.1"
},
"dependencies": {
"actions-on-google": "^1.0.0"
},
"devDependencies": {
"semistandard": "^9.1.0"
}
}
After a log of searching I found the correct setup.
Here is the correct app.js code:
'use strict';
process.env.DEBUG = 'actions-on-google:*';
let Assistant = require('actions-on-google').ApiAiAssistant;
let bodyParser = require('body-parser');
let app = express();
app.use(bodyParser.json({type: 'application/json'}));
app.post('/', function (req, res) {
// Todo
});
if (module === require.main) {
// Start the server
let server = app.listen(process.env.PORT || 8080, function () {
let port = server.address().port;
console.log('App listening on port %s', port);
});
}
module.exports = app;

mongodb connection timeout error with mongoose and nodejs

I desperately need some help.I am trying to upload large file(8 GB) to gridfs using mongoose and nodeJS. But as the file is very large it takes some time to upload. And after a while I get the following error:
home/user/FileUpload/node_modules/mongodb/lib/utils.js:98
process.nextTick(function() { throw err; });
^
MongoError: connection 0 to 127.0.0.1:27017 timed out
at Function.MongoError.create (/home/user/FileUpload/node_modules/mongodb-core/lib/error.js:29:11)
at Socket.<anonymous> (/home/user/FileUpload/node_modules/mongodb-core/lib/connection/connection.js:186:20)
at Object.onceWrapper (events.js:314:30)
at emitNone (events.js:105:13)
at Socket.emit (events.js:207:7)
at Socket._onTimeout (net.js:402:8)
at ontimeout (timers.js:488:11)
at tryOnTimeout (timers.js:323:5)
at Timer.listOnTimeout (timers.js:283:5)
I have tried to resolve this by increasing connectTimeoutMS but the error still persist. I am using MongoDB 3.4.5 mongoose 4.8.4 nodejs 8.1.4 and npm 5.0.3.
Following is app.js:
var mongoose = require('mongoose');
var schema = mongoose.schema;
mongoose.connect('mongodb://127.0.0.1/gridFS'),{
server: {
socketOptions: {
socketTimeoutMS: 3000000,
connectionTimeoutMS: 3000000,
keepAlive:3000000
}
},
replset: {
socketOptions: {
keepAlive: 3000000,
connectTimeoutMS: 3000000
}
}
};
var conn = mongoose.connection;
var path = require('path');
var Grid = require('gridfs-stream');
var fs = require('fs');
var videoPath = path.join(__dirname, 'readFrom/bio seq test1.txt');
Grid.mongo = mongoose.mongo;
conn.once('open', function(){
console.log('- connection open -');
var gfs = Grid(conn.db);
var writestream = gfs.createWriteStream({
filename: 'bio seq test 1'
});
fs.createReadStream(videoPath).pipe(writestream);
writestream.on('close', function(file){
console.log(file.filename + 'Written to DB');
});
});
Following is package.json file:
{
"name": "file-upload-gridfs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo '' && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.16.1",
"cookie-parser": "^1.4.3",
"express": "^4.14.1",
"gridfs-stream": "^1.1.1",
"mongoose": "^4.8.4",
"morgan": "^1.8.2",
"multer": "1.3.0",
"multer-gridfs-storage": "1.0.0",
"path.join": "^1.0.0",
"serve-favicon": "^2.4.3"
}
}
Ok. I figured out the problem using this really helpful discussion.The default socket connection time for MongoDB is 30 seconds. If any query/operation takes longer than this the connection is aborted and connection timeout error occurs.
With this change I was able to upload a 32GB file to GridFS without any interruption.
https://github.com/Automattic/mongoose/issues/4789
I was passing the timeout parameter in following way.
server: {
socketOptions: {
socketTimeoutMS: 3000000,
connectionTimeoutMS: 3000000,
keepAlive:3000000
}
},
replset: {
socketOptions: {
keepAlive: 3000000,
connectTimeoutMS: 3000000
}
}
};
But it needs to be set in the following way:
const serverOptions = {
poolSize: 100,
socketOptions: {
socketTimeoutMS: 6000000
}
};
mongoose.createConnection(dbpath, {
server: serverOptions,
replset: serverOptions //if you are using replication
});
In my case I have used localhost.
const serverOptions = {
poolsize:100 ,
socketOptions:{
socketTimeoutMS: 6000000
}
};
var mongodbUri = 'mongodb://localhost:27017/gridFS';
mongoose.connect(mongodbUri, {
server: serverOptions
});
Hope this will help anyone with similar issue.

Categories

Resources