Can I tell foreman to reload the web app every time a request is made so I can develop decently?

后端 未结 6 700
南方客
南方客 2020-12-24 13:18

A web app I am writing in JavaScript using node.js. I use Foreman, but I don\'t want to manually restart the server every time I change my code. Can I tell Foreman to reload

相关标签:
6条回答
  • 2020-12-24 14:05

    Here's an adjusted version of Pendlepants solution. Foreman looks for an .env file to read environment variables. Rather than adding a wrapper, you can just have Foreman switch what command it uses to start things up:

    In .env:

    WEB=node app.js
    

    In dev.env:

    WEB=supervisor app.js
    

    In your Procfile:

    web: $WEB
    

    By default, Foreman will read from .env (in Production), but in DEV just run this:

    foreman start -e dev.env
    
    0 讨论(0)
  • 2020-12-24 14:07

    You can use rerun for this purpose

    You might implement just 2 commands for this:

    1. gem install rerun
    2. rerun foreman start

    Then rerun will automatically restart process after any change in your files.

    0 讨论(0)
  • 2020-12-24 14:09

    If you use nodemon , you can do

    nodemon --exec "foreman start"
    
    0 讨论(0)
  • 2020-12-24 14:12

    The problem isn't with Foreman so much as it's with how node doesn't reload code on new requests. The solution is to use an npm package like supervisor along with an environment wrapper for Foreman.

    First, install supervisor:

    npm install -g supervisor
    

    Then, write a wrapper shell script that Foreman can call:

    if [ "$NODE_ENV" == "production" ]; then
      node /path/to/app.js
    else
      supervisor /path/to/app.js
    fi
    

    Set the wrapper script's permissions to executable by running chmod a+x /path/to/wrapper_script.sh

    Lastly, update foreman to use the wrapper script. So in your Procfile:

    web: /path/to/wrapper_script.sh
    

    Now when you run Foreman and your node app isn't running in production, it should reload on every request.

    0 讨论(0)
  • 2020-12-24 14:12

    You don't even need to install anything new if you use node-dev.

    Your .env file loaded from Procfile:

    NODECMD=node-dev
    

    Your Procfile:

    web: $NODECMD app/server.js
    

    Your foreman command

    foreman start -e dev.env -p 9786
    

    And in your production env (heroku) set an environment variable:

    NODECMD=node
    
    0 讨论(0)
  • 2020-12-24 14:14

    I feel like Peter Ehrlich's comment on the original question deserves to be an answer on its own. I think a different Procfile for local/dev is definitely the best solution: https://stackoverflow.com/a/10790514/133720

    0 讨论(0)
提交回复
热议问题