Wouldn't it be cool to run JavaScript on the server?
The user send a request to the server, the server send back a response.
node --version
index.js:
console.log("Hello World!");
node index.js
Hello World!
process.on("exit", () => { console.log("Goodbye!"); }); console.log("Hello World!");
Hello World! Goodbye!
const EventEmitter = require("events"); const eventEmitter = new EventEmitter(); eventEmitter.on("start", () => { console.log("Started!"); }); eventEmitter.on("end", () => { console.log("Ended!"); }); eventEmitter.emit("start"); eventEmitter.emit("end"); eventEmitter.emit("start");
Started! Ended! Started!
text.txt:
Hello World! I am a text file.
const { readFile } = require("fs"); readFile("./text.txt", "utf8", (err, data) => { if (err) { console.error(err); return; } console.log(data); }); console.log("Am I the second message ?");
Am I the second message ? Hello World! I am a text file.
const { readFile } = require("fs");
const add = (x, y) => { return x + y; }; const PI = 3.14159; module.exports = { add: add, PI: PI, };
const math = require("./math.js");
npm init --yes
. ├── index.js └── package.json
{ "name": "nodejs", "version": "1.0.0", "description": "Node.js course", "main": "index.js", "scripts": { "start": "node index.js" }, "keywords": [ "nodejs" ], "author": "Vincent Guidoux", "license": "MIT" }
npm install express
{ "name": "nodejs", "version": "1.0.0", "description": "Node.js course", "main": "index.js", "scripts": { "start": "node index.js" }, "keywords": [ "nodejs" ], "author": "Vincent Guidoux", "license": "MIT", "dependencies": { "express": "^4.17.1" } }
nodemon is a tool that helps develop Node.js based applications by automatically restarting the node application when file changes in the directory are detected.
npm install --save-dev nodemon
{ "name": "nodejs", "version": "1.0.0", "description": "Node.js course", "main": "index.js", "scripts": { "start": "node index.js", "dev": "npx nodemon index.js 3000" }, "keywords": [ "nodejs" ], "author": "Vincent Guidoux", "license": "MIT", "dependencies": { "express": "^4.17.1" }, "devDependencies": { "nodemon": "^2.0.15" } }
const express = require('express'); const { readFile } = require('fs'); const app = express(); app.get('/', (req, res) => { readFile('./home.html', 'utf8', (err, html) => { if (err) { res.status(500).send('sorry, out of order'); } res.send(html); }) }); app.listen(process.env.PORT || 3000, () => console.log('App available on http://localhost:3000'));
FROM node:20-alpine as build WORKDIR /app COPY package.json package.json COPY package-lock.json package-lock.json RUN npm ci --omit=dev COPY home.html home.html COPY index.js index.js EXPOSE 3000 CMD ["npm", "run", "start"]
This is a way to make link and shortcut in the code
This comment will center everything on the page