NodeJS

npm

Initialisation d'un projet express.js

Source : https://dev.to/nyctonio/how-to-make-a-typescript-nodejs-express-project-with-eslint-ejs-and-nodemon-hot-reload-4e0b

yarn init -y
yarn add -D eslint @types/node @types/express typescript ts-node-dev
mkdir src
touch src/app.ts

src/app.ts :

import express from 'express';
const app = express();
const port = 3000;
app.use(express.json());
app.use(express.static("public"));
app.set("view engine", "ejs");

app.get('/', (req, res) => {
  res.send('Hello World !');
});

app.listen(port, () => {
  return console.log(`http://localhost:${port}`);
});
touch tsconfig.json

tsconfig.json :

{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist"
  },
  "lib": [
    "es2015"
  ]
}
yarn eslint --init

package.json :

{
  "name": "app",
  "version": "1.0.0",
  "description": "",
  "keywords": [],
  "author": "",
  "license": "MIT",
  "main": "dist/app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "lint": "eslint . --ext .ts",
    "start": "ts-node-dev src/app.ts"
  },
  "devDependencies": {
    "@types/express": "^4.17.14",
    "@types/node": "^18.11.9",
    "@typescript-eslint/eslint-plugin": "^5.43.0",
    "@typescript-eslint/parser": "^5.43.0",
    "eslint": "^8.28.0",
    "ts-node-dev": "^2.0.0",
    "typescript": "^4.9.3"
  },
  "dependencies": {
    "ejs": "^3.1.8",
    "express": "^4.18.2"
  }
}
yarn start

Commandes utiles

Liens pour le développement de modules

npm install -g symlink
cd application
symlink ../
Pour appliquer les modifications
symlink --execute ../

Problème d'authentification lors de l'installation d'un package depuis un dépôt privé

git config --global credential.helper cache
git ls-remote https://exemple.com/user/repo
npm install git+https://exemple.com/user/repo

Ecriture d'un module avec mise en cache de données

import fs from 'node:fs';

let isDockerCached;

function hasDockerEnv() {
	try {
		fs.statSync('/.dockerenv');
		return true;
	} catch {
		return false;
	}
}

function hasDockerCGroup() {
	try {
		return fs.readFileSync('/proc/self/cgroup', 'utf8').includes('docker');
	} catch {
		return false;
	}
}

export default function isDocker() {
	// TODO: Use `??=` when targeting Node.js 16.
	if (isDockerCached === undefined) {
		isDockerCached = hasDockerEnv() || hasDockerCGroup();
	}

	return isDockerCached;
}