update nodejs langauge guide (#17659)

Signed-off-by: Craig Osterhout <craig.osterhout@docker.com>
This commit is contained in:
Craig Osterhout 2023-07-05 07:16:22 -07:00 committed by GitHub
parent f583cadd22
commit 633c6be951
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 13 deletions

View File

@ -166,7 +166,7 @@ To start our application in debug mode, we need to add a line to our `package.js
Open the `package.json` file and add the following line to the scripts section:
```json
"debug": "nodemon --inspect=0.0.0.0:9229 server.js"
"debug": "nodemon --inspect=0.0.0.0:9229 -L server.js"
```
As you can see, we are going to use nodemon. Nodemon starts our server in debug mode and also watches for files that have changed, and restarts our server. Lets run the following command in a terminal to install nodemon into our project directory.

View File

@ -77,7 +77,7 @@ Okay, now that we know our application is running properly, lets try and run
...
"scripts": {
"test": "mocha ./**/*.js",
"start": "nodemon --inspect=0.0.0.0:9229 server.js"
"start": "nodemon --inspect=0.0.0.0:9229 -L server.js"
},
...
}
@ -87,22 +87,43 @@ Below is the Docker command to start the container and run tests:
```console
$ docker compose -f docker-compose.dev.yml run notes npm run test
Creating node-docker_notes_run ...
```
> node-docker@1.0.0 test /code
When you run the tests, you should get an error like the following:
```console
> mocha ./**/*.js
Array
#indexOf()
✓ should return -1 when the value is not present
1 passing (11ms)
sh: mocha: not found
```
The current Dockefile does not install dev dependencies in the image, so mocha cannot be found. To fix this, you can update the Dockerfile to install the dev dependencies.
```dockerfile
# syntax=docker/dockerfile:1
FROM node:18-alpine
ENV NODE_ENV=production
WORKDIR /app
COPY ["package.json", "package-lock.json*", "./"]
RUN npm install --include=dev
COPY . .
CMD ["node", "server.js"]
```
Run the command again, and this time rebuild the image to use the new Dockerfile.
```console
$ docker compose -f docker-compose.dev.yml run --build notes npm run test
```
This image with dev dependencies installed is not suitable for a production image. Rather than creating multiple Dockerfiles, we can create a multi-stage Dockerfile to create an image for testing and an image for production.
### Multi-stage Dockerfile for testing
In addition to running the tests on command, we can run them when we build our image, using a multi-stage Dockerfile. The following Dockerfile will run our tests and build our production image.