Starting Express.js Using app.js or 'npm start'?

27,144

Solution 1

Thank you all for your great responses, as they really allowed me to understand what is actually going on with the app.js file and where it receives it's functionality. Thank you to both Matthew Bakaitis and Bjarni Leifsson for their great input.

The only reason why I am going to go ahead and answer my own question is because while the nature of the app.js file was explained, exactly how to replicate calling the 'node app.js' command from the command line as to replicate a Node.js book that I was following wasn't implicitly addressed.

After searching google with the specific phrase "app.js in previous express.js versions", I happened upon a great article by Jilles Soeters entitled "Understanding the Express app.js":

http://jilles.me/getting-the-express-app-js/

Below is the excerpt of the solution that worked for me:

The file I'm covering is app.js, the main configuration file for your Express app. When I first opened app.js it confused me. I will save you the trouble of doing research and just cover them here.

Before you do anything add the following to your app.js

app.listen(3000);

You need that in order to be able to actual open your app in the browser. Go to 127.0.0.1:3000 after you've started your app (using node app.js)

After doing this, I was able to run the command

node app.js

I was able to run this command from the root directory of the Express install and proceed with my Node.js book with no additional problems.

Solution 2

This is a common problem that is caused when tutorials don't clearly explain what express is doing when it generates an app. You're trying to learn the new tech, but the tutorial is actively working against you. :(

The answer:

When you use the generator, package.json is configured so that npm start calls ./bin/www.

That file includes app.js and after the include, calls app.listen.

app.js doesn't call app.listen which is why if you call it directly, it exits with no code or info. You've got to call ./bin/www or you have to modify app.js...which then defeats some of the reasons you'd use a generator.

A related question here on the site saw a similar problem when trying to use supervisor to keep an app running but kept getting an exit 0 result.

Solution 3

How I understand this, and I have just started to use node.

There is a bin folder with www in it. There all the magic happens. So when you do node app.js it gets executed but the logic to the everything is in bin/www

So if you look into package.json you see this init :

"scripts": { "start": "node ./bin/www" },

So giving that, you see to execute the script you use the start method and it is linked to ./bin/www

If you take a look in that file you will find out that the whole logic of the server to start up is in there.

So if you change start to something else, like TurnOn and would do npm TurnOn, it will execute ./bin/www and the whole project for you.

The structor of the project is all linked together, and app.js is not enough to start the server.

Hope this helps.

Solution 4

When using Express the Express instance will create the server for you. Typically your app/index/server.js file will begin with these lines:

const express = require('express');
const app = express();

These lines require Express and then instantiate an instance of Express within the app variable. Express then uses var server = http.createServer(app); to start a server for you. All you need to do is to make sure your app listens to that server (as you wrote). However, the port for the connection may vary so it is not advisable to hard-code it. Instead it should be retrieved from the app variable as such:

app.listen(app.get('port'), function(){
    //Something to do when the server starts.
});

Additionally, after creating your own app.js file make sure to change your package.json file to start the app via app.js instead of the Express module. By default your package.json might look like this:

"scripts": {
 "start": "node ./bin/www"
},

But after you created your own app/index/server.js file you want node to start running that file on startup instead:

"scripts": {
 "start": "node app.js"
}

You can then start your app by writing npm start from the project directory.

Share:
27,144
Mindsect Team
Author by

Mindsect Team

Running a great team over here at Mindsect. Legitimizing the choices our clients make through logistics consulting and industry analysis. I'm a PHP developer with knowledge of MySQL. Currently moving our larger applications over to Node.js with an emphasis on the MEAN stack of web app development. Nice to know ya!

Updated on September 06, 2020

Comments

  • Mindsect Team
    Mindsect Team over 3 years

    I've recently installed Node.js on a local server and when I create a 'server.js' file (adding a server using the .createServer() method), it loads fine.

    However after installing Express.js, the default files are as follows:

    /bin
    /node_modules
    /public
    /routes
    /views
    app.js
    package.json
    

    After following some documentation, I am instructed to go to Terminal and enter the following command:

    node app.js
    

    To which nothing happens, the command line refreshes to the next line in less than a second, and opening a browser after visiting the proper IP and port, to no avail.

    Below is the code inside of the app.js file:

    var express = require('express');
    var path = require('path');
    var favicon = require('serve-favicon');
    var logger = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    
    var routes = require('./routes/index');
    var users = require('./routes/users');
    
    var app = express();
    
    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');
    
    // uncomment after placing your favicon in /public
    //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));
    
    app.use('/', routes);
    app.use('/users', users);
    
    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
      var err = new Error('Not Found');
      err.status = 404;
      next(err);
    });
    
    // error handlers
    
    // development error handler
    // will print stacktrace
    if (app.get('env') === 'development') {
      app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
          message: err.message,
          error: err
        });
      });
    }
    
    // production error handler
    // no stacktraces leaked to user
    app.use(function(err, req, res, next) {
      res.status(err.status || 500);
      res.render('error', {
            message: err.message,
            error: {}
          });
        });
    
    module.exports = app;
    

    I understand that the actual 'express' module that is being required in the beginning of the file is where the magic happens, however, when I run the command line:

    node app.js
    

    Nothing happens. However, if I call the following line:

    npm start
    

    Everything appears to be okay. I would like to follow the documentation as is, any reason why the app.js wouldn't be working?

    Thank you.

    UPDATE: My question was too similar to another one already posted, so I must clarify exactly how they were different. In the other question, a person was questioning a code number they received while running the Supervisor command on the default 'app.js' file.

    While similar in nature, this question should remain, as those who are confused by using my same approach will focus on the identity of the actual 'app.js' file by using 'node app.js' without having full knowledge of the Supervisor utility.

    Regards.