Nodemon - "clean exit - waiting for changes before restart" during setup - javascript

I am trying to set up a RESTful API with Node and Postgres. I have run into a problem where whenever I attempt to run the server (using npm start) to test it locally, I get the following output:
[nodemon] 1.14.10 [nodemon] to restart at any time, enter rs [nodemon] watching: . [nodemon] starting node index.js server.js
[nodemon] clean exit - waiting for changes before restart
After searching online for quite some time, I cannot find too many resources on what exactly "clean exit - waiting for changes before restart" exactly means, especially in this case.
This is my queries.js file:
1 var promise = require('bluebird');
2
3 var options = {
4 // Initialization Options
5 promiseLib: promise
6 };
7
8 // created an instance of pg-promise, override default pgp lib w bluebird
9 var pgp = require('pg-promise')(options);
10 var connectionString = 'postgres://localhost:3000/actions';
11 var db = pgp(connectionString);
12
13 // add query functions
14
15 module.exports = {
16 getAllActions: getAllActions,
17 // getSingleAction: getSingleAction,
18 // createAction: createAction,
19 // updateAction: updateAction,
20 // removeAction: removeAction
21 };
22
23 function getAllActions(req, res, next) {
24 db.any('select * from acts')
25 .then(function (data) {
26 res.status(200)
27 .json({
28 status: 'success',
29 data: data,
30 message: 'Retrieved ALL actions'
31 });
32 })
33 .catch(function (err) {
34 return next(err);
35 });
36 }
Here is my index.js file:
3 var express = require('express');
4 var app = express();
5 var router = express.Router();
6 var db = require('./queries');
7
8 // structure: expressInstance.httpRequestMethod(PATH, HANDLER)
9 app.get('/api/actions', db.getAllActions);
10 //app.get('/api/actions/:id', db.getSingleAction);
11 //app.post('/api/actions', db.createAction);
12 //app.put('/api/actions/:id', db.updateAction);
13 //app.delete('/api/actions/:id', db.removeAction);
14
15 module.exports = router;
Any thoughts on what could be going on here? Thanks in advance.

There are a few things wrong with your code. You never told your app to run. When you're ready creating your routes you should start your server with:
app.listen(<port on which the server should run here>);
Also you have an Express app and a router in the same file. The router should only be used as a sub module (handy when you want to divide your app over multiple files). Right now you're doing nothing with it. If you remove the router and the export then it should work fine.

I am also wondering about this statement logged by nodemon. I experienced this only the last days. I get this error if some syntax error exists in my express server code. When I start the server via
> node server
the server does not start and even does not log anything to console.
Strange behaviour I think. It seems that this message has nothing to do with nodemon.
I never experienced such a thing with node in the past. Every time a syntax error was introduced I got an error message with the stack trace outputted to console.
As I said before it was just a syntax error: A closing bracket was missing from a .then block.
After all I do not know why node was not printing the stack trace as I have experienced it before.
I investigate further but one thing to learn from this kind of error is probably to use a linter for writing javascript code or go a step further and use TypeScript. I use TypeScript for developing the client with Angular and the possibilities to detect syntax errors early are great.

If anyone still has issues with this how I solved mine was that I discovered my database was not connected I'm using mongodb for my setup so setting up mongo with the mongod command and running the server again with either node app.js or nodemon app.js fixed mine

solution 1:
Firstly make sure you have included these lines of code for the Node-Express application,
// 3000 is the port number in my case.
app.listen(3000, function() {
console.log("Server is running on port " + 3000);
});
in your main file(i.e. app.js in my case) to start the server.
Solution 2:
Open your package.json file.
Check for the name of the file for the main field.
In my case it is
{...,"main": "app.js",...}.
This app.js is the primary entry point to the program.
Now, try to start your server with the following command,
nodemon app.js
or
node app.js
Solution 3:
If your program is running with,
node app.js
but, not with
nodemon app.js
Then, this problem is with nodemon.
If you have files with names as index.js and app.js in your project, then deleting index.js will resolve the issue.
If index.js is the entry point to your program, then try Solution 2 given above and change the main field value in the package.json file to index.js
i.e. {...,"main": "index.js",...}.
This will fix your issue.

I too had face the same issue.
Node version was 14.15.5.
so installed node 12.22 version and working fine.

I had the same issue but my problem was very simple newbie issue-adding it here in case those new to express and this type of code make the same mistake
I had unknowingly included the 'app.listen' within my 'app.get' code (yes I know, very basic mistake but it was frustrating, hence giving my option here)
Wrong way
app.get("/", (req, res) => {
res.send(req.query);
*....additional code here...*
app.listen(port, () => {
console.log("hey app is listening");
});
});
Right way-
app.get("/", (req, res) => {
res.send(req.query);
});
app.listen(port, () => {
console.log("hey app is listening");
});

Facing same problem, I just deleted the node_modules folder and package-lock.json file and reinstalled the dependencies and it worked.

app.listen(5010,function(){
console.log("server is running on port 5010");
});
// add the code above to resolve this issue

I had a similar issue after returning to one Node app (main file: app.js) after working on another Node app (main file: index.js).
If I entered
Nodemon app
I got a message like
[nodemon] starting `node app index.js`
[nodemon] clean exit - waiting for changes before restart
I played around with the version of Nodemon (update made no difference), I then tried entering
Node app
and got the usual proper working response, i.e.
[nodemon] 1.19.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node app.js`
HTTP server started at port 3000 ...
and I also got it going correctly when I entered
Nodemon app.js
Now, normally up to then it made no difference whether you enter app.js or app - but here it does seem to make a difference. Maybe some of the cached settings for the other Node app (i.e. the one using index.js as a main script and using app as an object within that file) were being retained and referenced to somehow.
Are there any Nodemon proficient people here to explain this ?

and your program will show the error on browser refused to connect than try this code on terminal if you using express generator
npm start
or
nodemon start

After many hours of looking for a solution why my production node-build in docker always immediately stops with exit 0 I found out that the node-version of the docker-images is incompatible. If you face this problem in docker try out different node-versions

[nodemon] starting node index.js
URI malformed
[nodemon] clean exit - waiting for changes before restart
I was able to fix this by changing the '#' symbol in my password for the connection url to %40

This is 2022, so if anyone still has this error, here's a fix that worked for me.
Make sure that your "start" command in "scripts" package.json is pointing to your entry file for the application.
`
"scripts": {
"dev": "nodemon src/server.ts",
"start": "nodemon dist/server.js",
"postinstall": "tsc"
}
`

Did you invoke start? For me that was a problem in app.js.

[nodemon] clean exit - waiting for changes before restart ?
Ans: Check your internet connection,
When restart my app my connection is lost thats why it will give the this err...

Related

Node app working on localhost but not on Heroku?

I have a node.js app that is running fine when I do npm run dev (using nodemon) on my localhost. However when I deploy to heroku, it crashes every time.
I get an H10 error every time as well as this error:
Error: Cannot find module '../models/User'
I've tried all the usual remedies: my port is correct
const PORT = process.env.PORT || 5000;
I added a Procfile
I removed all my node_modules and put them in .gitignore
Yet I still get the crash.
I believe the line of code the error is referencing is in one of my routes, which is in the file index.js
const express = require('express');
const router = express.Router();
const { ensureAuthenticated } = require('../config/auth');
const mongoose = require('mongoose');
const User = require('../models/User'); //Line I believe is the issue
I need that line in order for my app to execute properly. Anyone have any suggestions?
EDIT- FOLDER STRUCTURE:
>config
>models
>User.js
>node_modules
>public
>routes
>index.js
>users.js
>views
>app.js
>package-lock.json
>package.json
>Procfile
I think the problem was due to case sensitivity and file nameing. Mac OS X is case insensitive (but aware) whereas Heroku is based on Linux and is case sensitive.
You can try rename User.js to user.js.
By running heroku run bash from your terminal, then ls ./models/, you can see how the /models folder appeared on Heroku's file system.
You need app.yaml file in your root folder.
env: flex
runtime: nodejs
api_version: '1.0'

npm start run error "var before = prev.prev || {}; TypeError: Cannot read property 'prev' of undefined"

Currently I am trying to run a very basic to do list using node. After setting up package.json and server.js, I ran npm start run, but I am getting a weird error.
UPDATE:
Here is the basic code and .json file:
enter image description here
var express = require('express'),
app = express(),
port =process.env.PORT ||3000;
app.listen(port);
console.log('todo list RESTful API server started on: ' + port);
This is the error:
This is the complete log page:
I ran into the same problem with nodemon when running my test scripts in a node.js api.
It seems the error is related to this issue with nanomatch, a package nodemon uses, a link to the issue: https://github.com/micromatch/nanomatch/issues/15.
I solved it with the following steps:
Verify the version of nanomatch in node_modules/nanomatch/package.json if the version is 1.2.11 (I also had a similar issue with 1.2.9) you need to change its version.
Run npm i nanomatch#1.2.13 (--save or --save-dev according to your situation)
After these steps nodemon worked for me. Hope that helps.

Node JS ctrl + C doesn't stop server (after starting server with "npm start")

When I start my server with node app.js in the command line (using Git Bash), I can stop it using ctrl + C.
In my package.json file i got this start-script that allows me to use the command npm start to start the server:
"scripts": {
"start": "node app"
},
When I do this, the server starts as normal:
$ npm start
> nodekb#1.0.0 start C:\Projects\nodekb
> node app.js
Server started on port 3000...
But when i ctrl + C now, the server does not get stopped (the node process still remains in task manager). This means that I get an error when I try to do npm start again, because port 3000 is still being used.
I'm following a tutorial on youtube (video with timestamp), and when this guy ctrl + C and then runs npm start again, it works as normal.
Any ideas why my server process is not stopped when I use ctrl + C?
My app.js file if needed:
var express = require("express");
var path = require("path");
//Init app
var app = express();
//Load View Engine
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
//Home Route
app.get("/", function(req, res) {
res.render("index", {
title: "Hello"
});
});
//Add route
app.get("/articles/add", function (req, res) {
res.render("add_article", {
title: "Add Article"
});
});
//Start server
app.listen(3000, function() {
console.log("Server started on port 3000...");
});
Thanks!
Ctrl + C does not kill the server. The resolution to the issue was using following code snippet in server.js:
process.on('SIGINT', function() {
console.log( "\nGracefully shutting down from SIGINT (Ctrl-C)" );
// some other closing procedures go here
process.exit(0);
});
This worked for me.
You can also check for other solutions mentioned at Graceful shutdown in NodeJS
I tried it on normal windows cmd, and it worked as it should there. Looks like it's a problem with git bash.
I encountered this problem in MSYS2 proper, even in latest build (x64 2018-05-31).
Luckily, Git for Windows maintain a customized MSYS2 runtime. They have patches that have not been sent upstream, including a patch that fixes emulation of SIGINT, SIGTERM and SIGKILL.
Discussion: https://github.com/nodejs/node/issues/16103
I was able to make my "MSYS2 proper" platform use Git for Windows' MSYS2 runtime, by following these instructions.
Repeated here for posterity:
Install inside MSYS2 proper
This guide assumes that you want the 64-bit version of Git for Windows.
Git for Windows being based on MSYS2, it's possible to install the git package into an existing MSYS2 installation. That means that if you are already using MSYS2 on your computer, you can use Git for Windows without running the full installer or using the portable version.
Note however that there are some caveats for going this way. Git for Windows created some patches for msys2-runtime that have not been sent upstream. (This had been planned, but it was determined in issue #284 that it would probably not be happening.) This means that you have to install Git for Windows customized msys2-runtime to have a fully working git inside MSYS2.
Here the steps to take:
Open an MSYS2 terminal.
Edit /etc/pacman.conf and just before [mingw32] (line #71 on my machine), add the git-for-windows packages repository:
[git-for-windows]
Server = https://wingit.blob.core.windows.net/x86-64
and optionally also the MINGW-only repository for the opposite architecture (i.e. MINGW32 for 64-bit SDK):
[git-for-windows-mingw32]
Server = https://wingit.blob.core.windows.net/i686
Authorize signing key (this step may have to be repeated occasionally until https://github.com/msys2/msys2/issues/62 is fixed)
curl -L https://raw.githubusercontent.com/git-for-windows/build-extra/master/git-for-windows-keyring/git-for-windows.gpg |
pacman-key --add - &&
pacman-key --lsign-key 1A9F3986
Then synchronize new repository
pacboy update
This updates msys2-runtime and therefore will ask you to close the window (not just exit the pacman process). Don't panic, simply close all currently open MSYS2 shells and MSYS2 programs. Once all are closed, start a new terminal again.
Then synchronize again (updating the non-core part of the packages):
pacboy update
And finally install the Git/cURL packages:
pacboy sync git:x git-doc-html:x git-doc-man:x git-extra: curl:x
Finally, check that everything went well by doing git --version in a MINGW64 shell and it should output something like git version 2.14.1.windows.1 (or newer).
Note: I found that the git-extra package installed by step 7 was quite intrusive (it adds a message "Welcome to the Git for Windows SDK!" to every terminal you open), so I removed it with pacman -R git-extra.
Note 2: I also found that Git for Windows' MSYS2 runtime opens in a different home directory than did MSYS2 proper's. This also means it reads in the wrong bash profile. I fixed this by adding an environment variable to Windows in the Control Panel: HOME=/C/msys64/home/myusername
I use git bash on my Windows machine and have run into this issue in the last month or so.
I still do not know what's causing it but I've found another way to stop it.
Open Task Manager
Go into the Processes tab
Look for node.exe and then press End Process
This has allowed me to stop the server quickly.
I had the same problem working with npm. But finally, I knew it was a problem with git itself.
There was a comment by dscho on GitHub 15 days ago. He said that they're working to fix this problem in the next release. He also shared the exact msys-2.0.dll file that can fix the problem for the people who can't wait.
Personally, I couldn't wait :p. So, I gave it a try, downloaded the file, and throw it in the git folder as he said. And the problem gone! It was awesome!
But please be sure to take a backup before you replace the file.
I also tried to kill it after running express as I used to; using taskkill /im node.exe on the cmd but there was no process to be found.
Check out this issue on GitHub,and search for the name of the file msys-2.0.dll to get to the comment faster.
Sometimes the node process hangs.
Check for the process ID using ps You may want to grep for node and then kill the process using kill -9 [PID]
Use Ctrl+\ to send the SIGQUIT signal. It will close the server.
Reference - https://en.wikipedia.org/wiki/Signal_(IPC)
I was able to fix this by switching to nodemon to run the server.
npm install --save-dev nodemon
package.json:
"scripts": {
"start": "nodemon app"
},
I was trying to get json-server to quit a custom server script, but it always left a child process running on Windows. It seems to be a specific problem running express via npm on Windows. If you run the server directly via the c:>node server.js then it seems to quit correctly.
I was able to debug this issue by checking the ports using TCP View, and realizing that my Node server was running even though I had pressed ctrl-C to stop it. I suggest killing the terminal you are running node from entirely.
Use Ctrl + C, then input: >pm2 stop all
This will stop all server or when you get stack with nodejs.
Inside package.json under scripts I had this line react-scripts start&. Notice it ends with an & which would send the process to the background and ctrl+c will not work. Somehow trying to bring this to the foreground with fg also did not work. Solved the problem by removing the &.
if you use Node.js Exec Extention to run your project from f8,
you can use also f9 to cancel running..
This is more than likely just a problem with your console not accurately sending the command to the process. This is pretty common, especially when using third party consoles like cmdr / conemu.
The solution?
Just hit ctrl+c several times until it closes :P

Node.js and Forever "exited with code: 0"

CentOs 6.5 using root acount, I have a working Node.js Express app:
root#vps [/home/test/node]# npm start app.js
> test#0.0.1 start /home/test/node
> node ./bin/www app.js
The app can be seen working on the internet browser. I stop the app and try to run it with forever:
root#vps [/home/test/node]# forever start app.js
warn: --minUptime not set. Defaulting to: 1000ms
warn: --spinSleepTime not set. Your script will exit if it does not stay up for at least 1000ms
info: Forever processing file: app.js
root#vps [/home/test/node]#
Throws a couple of warnings that should not be a problem and looks like it should be working but its not showing on the browser, forever list:
root#vps [/home/test/node]# forever list
info: Forever processes running
data: uid command script forever pid id logfile uptime
data: [0] OkGm /usr/local/bin/node app.js 32222 32227 /root/.forever/OkGm.log STOPPED
root#vps [/home/test/node]#
If I check OkGm.log:
error: Forever detected script exited with code: 0
Why is the app not working when I run it with forever?
Ok I found out what was happening. I was trying to run:
forever start app.js
When this Express app must be started with:
forever start ./bin/www
There was no useful info on internet when searching for this by the error log output ("exited with code: 0"), so I hope this answer helps begginers like me in what I think can be an easy mistake to make.

why node.js process is killed?

I have developed one app in node.js. Recently I noticed when I am doing any changes in my "public" directory of my application, one error is recorded in my log file as follows:
error: restarting script because /home/{user}/workspace/{app_folder}/img/{filename}.jpg changed.
error: Forever detected script was killed by signal: SIGKILL
error: Forever restarting script for 1 time
Express server listening on port 3000
I have already set --watchIgnore parameter in my forever script file in /etc/init/{app}.config
env IGNORE_DIRECTORY="/home/{user}/workspace/{app_folder}/img/**"
exec forever --sourceDir $APPLICATION_DIRECTORY --watchIgnore $IGNORE_DIRECTORY \
-a -w -l $LOG --minUptime 5000 --spinSleepTime 2000 \
start $APPLICATION_START
What am I missing?
Note that the log shows {user} and not your actual user directory. This path looks like it was copied from a user guide, where you were meant to replace those quasi-variables with something.
You use bash environment variables (I assume you're using bash) like this:
env IGNORE_DIRECTORY="~/workspace/${APPLICATION_DIRECTORY}/img/**"
It looks like app_folder is actually defined for you as APPLICATION_DIRECTORY. You can also use ~/ as a shortcut for the current user's home folder.

Categories

Resources