Sunday, November 3, 2024

nodejs note

 

1. change package.json scripts to:

"start": "nodemon index.js"

so that when you run npm start, it can use nodemon to start it. Otherwise, you can use node directly use "node index.js".

2. serve static contents

create a directory 'static' and put a file page.html

app.use(express.static('static'))

now you can access http://localhost:3000/page.html

3. Express middleware functions. take three parameters, req, res, next

//log every requst to the terminal

app.use((req, res, next) => {

    console.log(req.url);

    next();

});

4.

app.use(compression());

app.disable('x-powered-by');

5.

CommonJS is the default (or set "type":"commonjs" in package.json)

setting "type":"module" in package.json parses the entry script as ESM (ES2015 modules)

ESM:

import {hello} from './two.mjs';

CommonJS:

const ehllo = require('.two.cjs');


No comments:

Post a Comment