Error: connect ECONNREFUSED 127.0.0.1:3000 when starting my app with nodemon

Viewed 1354

I'm very new to Node.js and I installed nodemon globally, but while when I start my app with npm start command in terminal I do get the message:

vinnytwice@Vinnys-iMac fixit_server_node % npm start

> fixit_server_node@1.0.0 start
> node server.js

App executing to port  3000

while if I use the command nodemon start in terminal I get:

vinnytwice@Vinnys-iMac fixit_server_node % nodemon start
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node start index.js`
[nodemon] clean exit - waiting for changes before restart

not showing any execution on any port, and in fact when hitting an endpoint I get Error: connect ECONNREFUSED 127.0.0.1:3000. If instead I start it with the command nodemon server.js then it does work.

Why npm start fired the server.js file and nodemon start doesn't? Is there something I shaven't set properly?

2 Answers

nodemon isn't a replacement of npm, they are totally different.
You can crudely think of nodemon being a drop in for node.

nodemon is a replacement wrapper for node. To use nodemon, replace the word node on the command line when executing your script.

Source: https://www.npmjs.com/package/nodemon

Hence if your npm script has,

"start": "node server.js"

Add another npm script,

"dev": "nodemon server.js"

You would want to use npm start in production environment and use npm run dev in development environment

You are seeing the ECONNREFUSED error because in your package.json there is a field,

"main": "index.js"

when you execute nodemon start, nodemon picks up this value and it actually runs node start index.js as shown in your logs.

If no script is given, nodemon will test for a package.json file and if found, will run the file associated with the main property

Source: https://www.npmjs.com/package/nodemon

Your index.js doesn't setup the server and hence when you try to access 127.0.0.1:3000 to hit your endpoints nothing is running there and hence you get ECONNREFUSED error

Notice this line

starting `node start index.js`

The output of your command nodemon start states that the file index.js is executed instead of server.js. You need to check your package.json file to see what is the main file of the program.

From the npm page of nodemon here

If you have a package.json file for your app, you can omit the main script entirely and nodemon will read the package.json for the main property and use that value as the app.

nodemon will also search for the scripts.start property in package.json (as of nodemon 1.1.x).

Related