Live Reloading
When building applications (whether backend or frontend), it gets tiring to manually stop & restart the app when you make changes to the source code.
This guide shows you how you can monitor files for changes and have the app restart automatically.
This is not something specific to ambiorix, but it is extremely useful during my development process, so I saw it a good idea to have it included as part of the examples.
Prerequisites
In case you’d like to know, we won’t be writing any JavaScript.
Setup
You of course need to have an app. You can use any of the code in the previous examples. We will use a simple
server.R
file, which is also the entrypoint:library(ambiorix) <- Ambiorix$new() app $get("/", \(req, res){ app$send("Using {ambiorix}!") res }) $get("/about", \(req, res){ app$text("About") res }) $start() app
Change to your project’s root dir.
cd myproject
Initialize an npm project & create the
package.json
file:npm init -y
The
-y
flag accepts the default npm setup.Install
nodemon
as a dev dependency:npm i -D nodemon
Create the file
nodemon.json
at the root dir of your project and paste this in it:{ "execMap": { "R": "Rscript" }, "ext": "*" }
This specifies an executable mapping for
.R
files:Rscript
.It also tells nodemon to monitor all files (
*
) for changes. You can as well monitor specific file extensions. For example to only watch.R
,.html
,.css
&.js
files, changeext
to:"ext": "R,html,css,js"
Open
package.json
and edit the “scripts” section to this:"scripts": { "dev": "nodemon --signal SIGTERM server.R" }
This tells nodemon to re-run the file
server.R
when changes happen.The
--signal SIGTERM
is basically telling nodemon to send a termination signal to the previously running program before spawning a new one. This is especially useful for freeing the port the app is running on, and then re-using it again.Run the app:
npm run dev
This runs the
dev
script which starts, stops & restarts your app when changes occurs.Now try making some changes to your source code and enjoy the experience.
When working on the backend, you don’t want a browser tab to open each time the app is restarted since you will mostly be sending requests via postman, so you will set
start(open = FALSE)
in yourserver.R
:library(ambiorix) <- Ambiorix$new() app $get("/", \(req, res){ app$send("Using {ambiorix}!") res }) $get("/about", \(req, res){ app$text("About") res }) $start(open = FALSE) app
To stop npm, press
CTRL
+C
.Add
node_modules/
to your.gitignore
file.You can as well add
nodemon.json
,package-lock.json
, &package.json
to.gitignore
since they’re just used for development purposes. I have commited them for this example just so you can see their contents.