What is Node.js

Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine.

Characteristics of 1.

Node.js can parse JS code (with no browser security level restrictions) and provides many system-level apis, such as:

  • File System reading and writing
  • Process management
  • Network Communication (HTTP/HTTPS)

2. For example

2.1 Restrictions on Browser security Levels

Ajax test

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>browser-safe-sandbox</title>
</head>
<body>
  <div>browser-safe-sandbox</div>
  <script>
    const xhr = new XMLHttpRequest()
    xhr.open('get'.'https://m.maoyan.com/ajax/moreClassicList?sortId=1&showType=3&limit=10&offset=30&optimus_uuid=A5518FF0AFEC11EAAB158D7AB 0D05BBBD74C9789D9F649898982E6542C7DD479&optimus_risk_level=71&optimus_code=10'.false)
    xhr.send()
  </script>
</body>
</html>
Copy the code

Browser preview

browser-sync start --server --files **/* --directory

2.2 File System Reading and Writing

const fs = require('fs')

fs.readFile('./ajax.png'.'utf-8'.(err, content) = > {
  console.log(content)
})
Copy the code

2.3 Process Management

function main(argv) {
  console.log(argv)
}

main(process.argv.slice(2))
Copy the code

run

node process.js argv1 argv2

2.4 Network Communication (HTTP/HTTPS)

const http = require("http")

http.createServer((req,res) = > {
  res.writeHead(200, {
    "content-type": "text/plain"
  })
  res.write("hello nodejs")
  res.end()
}).listen(3000)
Copy the code

2. Node related tools

1. NVM: Node Version Manager

1.1 Installing the NVM on a Mac

https://github.com/nvm-sh/nvm/blob/master/README.md
Copy the code

1.2 Installing the NVM on Windows

nvm-windows
nodist
Copy the code

2. NPM: Node Package Manager

2.1 Global Installation Package

$ npm install forever --global (-g)
$ forever
$ npm uninstall forever --global
$ forever
Copy the code

Directory of the global installation package

  • Mac

    / Users/felix/NVM/versions/bin / / node/NVM each versionCopy the code
  • Windows

    C:\Users\ Your user name \AppData\Roaming\ NPM \node_modulesCopy the code

2.2 Installing the Package locally

$ cd ~/desktop
$ mkdir gp-project
$ cd gp-project
$ npm install underscore
$ npm list (ls)
Copy the code

2.3 Package. json Initialization

$ pwd
$ npm init -y
$ ls
$ cat package.json
Copy the code

2.4 use package. Json

$ npm install underscore --save
$ cat package.json
$ npm install lodash --save-dev
$ cat package.json
$ rm -rf node_modules
$ ls
$ npm install
$ npm uninstall underscore --save
$ npm list | grep underscore
$ cat package.json
Copy the code

2.5 Installing the package of the specified version

$PWD $NPM list $NPM info underscore $NPM view underscore versions $NPM install [email protected] $NPM list $NPM uninstall underscore $ npm listCopy the code

2.6 Updating the locally installed packages

$NPM info the underscore $NPM view the underscore versions $NPM install [email protected] - save - $NPM dev list | grep gulp $ NPM outdated / / ~ 2.0.0 said patch, ^ 2.0.0 said minor * says the latest version of the $xx NPM list | grep gulp $NPM updateCopy the code

2.7 Clearing cache

npm cache clean --force
Copy the code

2.8 Uploading your Own Package

2.8.1 Writing modules

Save as the index. Js

exports.sayHello = function(){ 
  return 'Hello World'; 
}
Copy the code
2.8.2 Initializing the package description file

$ npm init package.json

{ 
  "name": "gp19-npm"."version": "1.0.1"."description": "gp19 self module"."main": "index.js"."scripts": { 
    "test": "make test" 
  }, 
  "repository": { 
    "type": "Git"."url": "git+https://github.com/lurongtao/gp19-npm.git" 
  }, 
  "keywords": [ 
    "demo"]."author": "Felixlu"."license": "ISC"."bugs": { 
    "url": "https://github.com/lurongtao/gp19-npm/issues" 
  }, 
  "homepage": "https://github.com/lurongtao/gp19-npm#readme",}Copy the code
2.8.3 Registering an NPM warehouse Account
The account felix_lurt/qqmko09ijn $NPM adduser at https://www.npmjs.comCopy the code
2.8.4 upload package
$ npm publish
Copy the code

Pit: 403 Forbidden

View the NPM source: NPM config get registry switch NPM source method one: NPM config set switch NPM registry http://registry.npmjs.org source method 2: NRM use NPMCopy the code
2.8.5 installation package
$ npm install gp19-npm
Copy the code
2.8.6 uninstall packages
See which packages are referenced by the current project: NPM ls Unpublish package: NPM unpublish --forceCopy the code
2.8.7 Using imported Packages
var hello = require('gp19-npm')
hello.sayHello()
Copy the code

2.9 NPM script

Node development is inseparable from NPM, and scripting is one of the most powerful and commonly used features of NPM.

2.9.1 What is an NPM Script?

NPM allows you to define script commands using the scripts field in package.json files.

{
  // ...
  "scripts": {
    "build": "node build.js"}}Copy the code
2.9.2 Execution Sequence

If multiple tasks need to be executed in an NPM script, you need to know in what order they should be executed.

script1.js

var x = 0
console.log(x)
Copy the code

script2.js

var y = 0
console.log(y)
"scripts": {
  "script1": "node script1.js"."script2": "node script2.js"
}
Copy the code

If the execution is parallel (that is, parallel execution at the same time), you can use the ampersand symbol.

$ npm run script1 & npm run script2
Copy the code

If the execution is secondary (that is, the next task is executed only if the previous one succeeds), you can use the && symbol.

$ npm run script1 && npm run script2
Copy the code
2.9.4 Short form

Commonly used shorthand for NPM scripts.

NPM start is NPM run startCopy the code
2.9.5 variable

One very powerful feature of NPM scripts is the ability to use NPM internal variables.

First, the NPM script can retrieve the fields in package.json with the npm_package_ prefix. For example, here is a package.json.

Note: It must be run in an NPM script (e.g., NPM run view). Running JS directly from the command line (e.g., node view.js) will not get the value

{
  "name": "foo"."version": "1.2.5"."scripts": {
    "view": "node view.js"}}Copy the code

So, the variable npM_package_name returns foo, and the variable npM_package_version returns 1.2.5.

// view.js
console.log(process.env.npm_package_name); // foo
console.log(process.env.npm_package_version); / / 1.2.5
Copy the code

In the above code, we get the package.json field values from the environment variable process.env. If it is a Bash script, you can get both values with npmpackagename and npM_package_name and npMPackagename and npM_package_version.

The npmpackage prefix also supports nested package.json fields.

"repository": {
  "type": "git"."url": "xxx"
},
scripts: {
  "view": "echo $npm_package_repository_type"
}
Copy the code

In the above code, the type property of the repository field can be repository_type by means of npM_package_repository_type.

Here’s another example.

"scripts": {
  "install": "foo.js"
}
Copy the code

In the above code, the value of the npm_package_scripts_install variable is equal to foo.js.

The NPM script can then retrieve the NPM configuration variable, the value returned by the NPM config get XXX command, via the npmconfig prefix. For example, the release tag of the current module can be fetched through nPM_config_tag.

"view": "echo $npm_config_tag",
Copy the code

Note that the config object in package.json can be overridden by environment variables.

{   "name" : "foo"."config" : { "port" : "8080" },  "scripts" : { "start" : "node server.js" }}
Copy the code

In the above code, the npM_package_config_port variable returns 8080. This value can be overridden by the following method.

$ npm config set foo:port 80
Copy the code

Finally, the env command lists all environment variables.

“env”: “env”

2.10 NPM Installs packages published on Git

NPM install git+https://[email protected]:lurongtao/gp-project.git# git+ssh://[email protected]:lurongtao/gp-project.gitCopy the code

2.11 cross – env

2.11.1 What is cross-env

Run scripts that set up cross-platform and use environment variables

2.11.2 Causes

Most Windows command prompts will block (error) when you use NODE_ENV=production to set environment variables. (The exception is Bash on Windows, which uses native Bash.) In other words, Windows does not support the NODE_ENV=production setup.

2.11.3 solve

Cross-env lets you use a single command without having to worry about setting up or using environment variables correctly for the platform. This mini-package (cross-env) provides a script for setting environment variables, allowing you to set environment variables in Unix mode and then run compatible on Windows.

2.11.4 installation

npm install –save-dev cross-env

2.11.5 use
{  "scripts": {    "build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"  }}
Copy the code

The NODE_ENV environment variable will be set by cross-env to print process.env.node_env === ‘production’

3, NRM: NPM Registry Manager

3.1 Manually Switching sources

3.1.1 Viewing the Current Source
npm config get registry
Copy the code
3.1.2 Switch to Taobao source
npm config set registry https://registry.npm.taobao.org
Copy the code

3.2 NRM Management Sources

NRM (NPM Registry Manager) is the mirror source management tool of NPM. Sometimes foreign resources are too slow, so it can be used to quickly switch between NPM sources.

3.2.1 installation NRM

On the cli, run the NPM install -g NRM command to install NRM globally.

3.2.2 use NRM

Run the NRM ls command to view the available sources. Where * is the current source in use, and the output above indicates that the current source is the official source.

3.2.3 switch NRM

To switch to the Taobao source, run the NRM use Taobao command.

3.2.4 Test speed

You can also use the NRM test to test the response time of the corresponding source.

nrm test
Copy the code

4. NPX: NPM Package Extention

NPM has added the NPX command since version 5.2. This article describes the main usage scenarios of this command.

Node has its own NPM module, so you can use the NPX command directly. In case it doesn’t work, install it manually.

$ npm install -g npx
Copy the code

4.1 Invoking modules installed by the project

The main problem NPX is trying to solve is to call modules installed inside the project. For example, Mocha is installed inside the project.

$ npm install -D mocha
Copy the code

In general, Mocha can only be called in the scripts fields of project scripts and package.json. If you want to call Mocha from the command line, you must do something like this.

$node-modules/.bin/mocha --versionCopy the code

NPX is intended to solve this problem by making it easier to use modules installed inside the project, simply by calling them as follows.

$ npx mocha --version
Copy the code

NPX checks for the presence of the command in node_modules/. Bin and the environment variable $PATH.

Since NPX checks the environment variable $PATH, system commands can also be invoked.

# = ls$NPX lsCopy the code

Note that the commands built into Bash are not in $PATH, so they don’t work. For example, CD is the Bash command, so you can’t use NPX CD.

4.2 Avoiding Global Module Installation

In addition to calling project internal modules, NPX can also avoid globally installed modules. For example, the create-react-app module is installed globally, and NPX can run it without global installation.

$ npx create-react-app my-react-app
Copy the code

While the above code is running, NPX downloads create-react-app to a temporary directory to be used and deleted later. If you run the preceding command again, create-react-app will be downloaded again.

Note that modules with the same name will be downloaded as long as the modules following the NPX cannot be found locally. For example, if the HTTP-server module is not installed locally, the following command will automatically download the module and start a Web service in the current directory.

$ npx http-server
Copy the code

4.3 –no-install parameter and –ignore-existing parameter

If you want NPX to force the use of local modules instead of downloading remote ones, use the –no-install parameter. If the module does not exist locally, an error is reported.

$ npx --no-install http-server
Copy the code

Conversely, if you ignore a local module of the same name and force the installation to use a remote module, you can use the –ignore-existing argument. For example, if you already have http-Server installed locally but still want to use remote modules, use this parameter.

$ npx --ignore-existing http-server
Copy the code

Modules/packages with CommonJS

1. Module/package classification

Node.js has three types of modules: built-in modules, third-party modules, and custom modules.

1.1 Built-in modules

Node.js built-in module is also called core module, node.js can be used directly after installation. Such as:

const path = require('path')var extname = path.extname('index.html')console.log(extname)
Copy the code

1.2 Third-party Node.js module

A third-party Node.js module is a module published on nPMjs.org for the purpose of implementing some function and available to the community under an open source license. Such as:

npm install chalkconst chalk = require('chalk')console.log(chalk.blue('Hello world! '))Copy the code

1.3 Custom Node.js module

Custom Node.js modules, also known as file modules, are modules that we write for our own use. At the same time, such modules are published on npmjs.org as open source third-party modules.

Custom modules are dynamically loaded at run time, which requires complete path analysis, file location, compilation and execution process. The speed is slightly slower than core modules, but it is used very much.

1.3.1 Module definition, interface exposure, and reference interface

We can separate common functions into a single JS file as a module. By default, methods or properties in this module are not accessible outside the module. To make methods or attributes accessible to the outside world, you must expose properties or methods inside the module through exports or module.exports.

M1. Js:

const name = 'gp19'const sayName = () = > {  console.log(name)}console.log('module 1')Module. exports = {say: sayName}// exports. exports = {say: sayName}// exports.say = sayName! exports = { say: sayName}
Copy the code

The main. Js:

const m1 = require('./m1')m1.say()
Copy the code
1.3.2 Circular reference of modules

Due to the wrong way of using exports, when two different JS are referenced in a loop, one JS cannot get the method of another JS, which results in execution error. Such as:

  • a.js
exports.done = false
const b = require('./b.js')
console.log('in a, b.done = %j', b.done)
exports.done = true
console.log('a done')
Copy the code
  • b.js
console.log('b starting')
exports.done = false
const a = require('./a.js')
console.log('in b, a.done = %j', a.done)
exports.done = true
console.log('b done')
Copy the code
  • main.js
console.log('main starting')
const a = require('./a.js')
const b = require('./b.js')
console.log('in main, a.done = %j, b.done = %j', a.done, b.done)
Copy the code

Const b = require(‘./b.js’); const b = require(‘./b.js’); Const a = require(‘./a. Js ‘); To prevent infinite loops, return an incomplete copy of A.js ports to the B.js module. B. js then completes the loading and provides its exported objects to the A. js module.

NodeJs has a wrapper around each js file called module. Module exports has an attribute that returns module.exports when require(‘a.js’). Module. exports is initialized to a {} empty object, so in the above example, const a = require(‘./a.js’); B. Exports does not load new a Module exports, but does not load the unloaded A Module exports to B Module. {done:false}, while a. exports. Done was set to true in b. exports. Done was set to false in b. exports. Nodejs solves the problem of loop references by returning an unfinished exports object.

Four, commonly used built-in modules

Here are some common built-in modules: URL, QueryString, HTTP, events, FS, Stream, readline, crypto, zlib

1, the url

1.1 the parse

url.parse(urlString[, parseQueryString[, slashesDenoteHost]])

const url = require('url')
const urlString = 'https://www.baidu.com:443/ad/index.html?id=8&name=mouse#tag=110'
const parsedStr = url.parse(urlString)console.log(parsedStr)
Copy the code

1.2 the format

url.format(urlObject)

const url = require('url')
const urlObject = {
    protocol: 'https:'.slashes: true.auth: null.host: 'www.baidu.com:443'.port: '443'.hostname: 'www.baidu.com'.hash: '#tag=110'.search: '? id=8&name=mouse'.query: { id: '8'.name: 'mouse' },
    pathname: '/ad/index.html'.path: '/ad/index.html? id=8&name=mouse'.href: 'https://www.baidu.com:443/ad/index.html?id=8&name=mouse#tag=110'
}
const parsedObj = url.format(urlObject)console.log(parsedObj)
Copy the code

1.3 resolve

url.resolve(from, to)

const url = require('url')
var a = url.resolve('/one/two/three'.'four')
var b = url.resolve('http://example.com/'.'/one')
var c = url.resolve('http://example.com/one'.'/two')
console.log(a + "," + b + "," + c)
Copy the code

2, the querystring

2.1 the parse

querystring.parse(str[, sep[, eq[, options]]])

const querystring = require('querystring')
var qs = 'x=3&y=4'
var parsed = querystring.parse(qs)
console.log(parsed)
Copy the code

2.2 stringify

querystring.stringify(obj[, sep[, eq[, options]]])

const querystring = require('querystring')
var qo = {  x: 3.y: 4}
var parsed = querystring.stringify(qo)
console.log(parsed)
Copy the code

2.3 the escape/unescape

querystring.escape(str)

const querystring = require('querystring')
var str = 'id = 3 & city = Beijing & url=https://www.baidu.com'
var escaped = querystring.escape(str)
console.log(escaped)
Copy the code

querystring.unescape(str)

const querystring = require('querystring')
var str = 'id%3D3%26city%3D%E5%8C%97%E4%BA%AC%26url%3Dhttps%3A%2F%2Fwww.baidu.com'
var unescaped = querystring.unescape(str)
console.log(unescaped)
Copy the code

3, HTTP/HTTPS

3.1 the get

var http = require('http')
var https = require('https')
// 1. Interface 2
const server = http.createServer((request, response) = > {
    var url = request.url.substr(1)
    var data = ' '
    response.writeHeader(200, {
        'content-type': 'application/json; charset=utf-8'.'Access-Control-Allow-Origin': The '*'  
    })
    https.get(`https://m.lagou.com/listmore.json${url}`.(res) = > {
            res.on('data'.(chunk) = > data += chunk)
            res.on('end'.() = > {
                response.end(JSON.stringify({ret: true,  data}))
            })
        })})
    server.listen(8080.() = > {  console.log('localhost:8080')})
Copy the code

3.2 POST: Server submission (attack)

const https = require('https')
const querystring = require('querystring')
const postData = querystring.stringify({
    province: 'Shanghai'.city: 'Shanghai'.district: 'Baoshan'.address: Floor 2-4, Building 3, Wisdom 7 Cubic, 199 Tongji Branch Road.latitude: 43.0.longitude: 160.0.message: 'Looking for a small fish'.contact: '13666666'.type: 'sell'.time: 1571217561
})
const options = {
    protocol: 'https:'.hostname: 'ik9hkddr.qcloud.la'.method: 'POST'.port: 443.path: '/index.php/trade/add_item'.headers: {
        'Content-Type': 'application/x-www-form-urlencoded'.'Content-Length': Buffer.byteLength(postData)
    }}
function doPost() {
    let data 
    let req = https.request(options, (res) = > {
        res.on('data'.chunk= > data += chunk)
        res.on('end'.() = > {console.log(data)})
        })
    req.write(postData)
    req.end()}
    // setInterval(() => {// doPost()// }, 1000)
Copy the code

3.3 Cross domain: JSONP

const http = require('http')
const url = require('url')
const app = http.createServer((req, res) = > {
    let urlObj = url.parse(req.url, true)
    switch (urlObj.pathname) {
        case '/api/user':
            res.end(`${urlObj.query.cb}({"name": "gp145"})`)
            break
        default:
            res.end('404.')
            break
    }
})
app.listen(8080.() = > {  console.log('localhost:8080')})
Copy the code

3.4 Cross-domain: CORS

const http = require('http')
const url = require('url')
const querystring = require('querystring')

const app = http.createServer((req, res) = > {
    let data = ' '
    let urlObj = url.parse(req.url, true)
    res.writeHead(200, {
        'content-type': 'application/json; charset=utf-8'.'Access-Control-Allow-Origin': The '*'
    })
    req.on('data'.(chunk) = > {data += chunk})
    req.on('end'.() = > { responseResult(querystring.parse(data)) })
    function responseResult(data) {
        switch (urlObj.pathname) {
            case '/api/login':
                res.end(JSON.stringify({message: data}))
                break
            default:
                res.end('404.')
                break
        }
    }
})
app.listen(8080.() = > {  console.log('localhost:8080')})
Copy the code

3.5 Cross-domain: Middleware (HTTP-proxy-Middware)

const http = require('http')
const proxy = require('http-proxy-middleware')

http.createServer((req, res) = > {
  let url = req.url

  res.writeHead(200, {
    'Access-Control-Allow-Origin': The '*'
  })

  if (/^\/api/.test(url)) {
    let apiProxy = proxy('/api', { 
      target: 'https://m.lagou.com'.changeOrigin: true.pathRewrite: {
        '^/api': ' '}})// http-proy-middleware is used in Node.js
    apiProxy(req, res)
  } else {
    switch (url) {
      case '/index.html':
        res.end('index.html')
        break
      case '/search.html':
        res.end('search.html')
        break
      default:
        res.end('[404]page not found.')
    }
  }
}).listen(8080)
Copy the code

3.6 the crawler

const https = require('https')
const http = require('http')
const cheerio = require('cheerio')

http.createServer((request, response) = > {
  response.writeHead(200, {
    'content-type': 'application/json; charset=utf-8'
  })

  const options = {
    protocol: 'https:'.hostname: 'maoyan.com'.port: 443.path: '/'.method: 'GET'
  }

  const req = https.request(options, (res) = > {
    let data = ' '
    res.on('data'.(chunk) = > {
      data += chunk
    })

    res.on('end'.() = > {
      filterData(data)
    })
  })

  function filterData(data) {
    let $ = cheerio.load(data)
    let $movieList = $('.movie-item')
    let movies = []
    $movieList.each((index, value) = > {
      movies.push({
        title: $(value).find('.movie-title').attr('title'),
        score: $(value).find('.movie-score i').text(),
      })
    })

    response.end(JSON.stringify(movies))
  }

  req.end()
}).listen(9000)
Copy the code

4, the Events

const EventEmitter = require('events')

class MyEventEmitter extends EventEmitter {}

const event = new MyEventEmitter()

event.on('play'.(movie) = > {
  console.log(movie)
})

event.emit('play'.'Me and my Country')
event.emit('play'.Captain China)
Copy the code

5, the File System

const fs = require('fs')
const fsP = require('fs').promises

// Create a folder
fs.mkdir('./logs'.(err) = > {
  console.log('done.')})// Rename the folder
fs.rename('./logs'.'./log'.() = > {
  console.log('done')})// Delete the folder
fs.rmdir('./log'.() = > {
  console.log('done.')})// Write the content to the file
fs.writeFile(
  './logs/log1.txt'.'hello'.// Error priority callback function
  (err) = > {
    if (err) {
      console.log(err.message)
    } else {
      console.log('File created successfully')}})// Append to the file
fs.appendFile('./logs/log1.txt'.'\nworld'.() = > {
  console.log('done.')})// Read the contents of the file
fs.readFile('./logs/log1.txt'.'utf-8'.(err, data) = > {
  console.log(data)
})

// Delete files
fs.unlink('./logs/log1.txt'.(err) = > {
  console.log('done.')})// Write files in batches
for (var i = 0; i < 10; i++) {
  fs.writeFile(`./logs/log-${i}.txt`.`log-${i}`.(err) = > {
    console.log('done.')})}// Read file/directory information
fs.readdir('/'.(err, data) = > {
  data.forEach((value, index) = > {
    fs.stat(`. /${value}`.(err, stats) = > {
      // console.log(value + ':' + stats.size)
      console.log(value + ' is ' + (stats.isDirectory() ? 'directory' : 'file'))})})})// Read files synchronously
try {
  const content = fs.readFileSync('./logs/log-1.txt'.'utf-8')
  console.log(content)
  console.log(0)}catch (e) {
  console.log(e.message)
}

console.log(1)

// Read the file asynchronously
fs.readFile('./logs/log-0.txt'.'utf-8'.(err, content) = > {
  console.log(content)
  console.log(0)})console.log(1)

// Read the file asynchronously
fs.readFile('./logs/log-0.txt'.'utf-8').then(result= > {
  console.log(result)
})

// Read the file asynchronously
function getFile() {
  return new Promise((resolve) = > {
    fs.readFile('./logs/log-0.txt'.'utf-8'.(err, data) = >{ resolve(data) }) }) } ; (async() = > {console.log(await getFile())
})()

// Read the file asynchronously
const fsp = fsP.readFile('./logs/log-1.txt'.'utf-8').then((result) = > {
  console.log(result)
})

console.log(fsP)

// watch monitors file changes
fs.watch('./logs/log-0.txt'.() = > {
  console.log(0)})Copy the code

6, the Stream

const fs = require('fs')

const readstream = fs.createReadStream('./note.txt')
const writestream = fs.createWriteStream('./note2.txt')

writestream.write(readstream)
Copy the code

7, Zlib

const fs = require('fs')
const zlib = require('zlib')

const gzip = zlib.createGzip()

const readstream = fs.createReadStream('./note.txt')
const writestream = fs.createWriteStream('./note2.txt')

readstream
  .pipe(gzip)
  .pipe(writestream)

writestream.write(readstream)
Copy the code

8, ReadLine

const readline = require('readline')

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})

rl.question('What do you think of Node.js? '.(answer) = > {
  // TODO: Log the answer in a database
  console.log(`Thank you for your valuable feedback: ${answer}`)

  rl.close()
})
Copy the code

9, Crypto

const crypto = require('crypto')

const secret = 'abcdefg'
const hash = crypto.createHmac('sha256', secret)
                   .update('I love you')
                   .digest('hex')
console.log(hash)
Copy the code

Four, routing,

var http = require('http')
var fs = require('fs')

http.createServer( function ( req, res ) {

  switch ( req.url ) {
    case '/home':
      res.write('home')
      res.end()
      break
    case '/mine':
      res.write('mine')
      res.end()
      break
    case '/login': 
      fs.readFile( './static/login.html'.function ( error , data ) {
        if ( error ) throw error  
        res.write( data )
        res.end()
      })
      break
    case '/fulian.jpg':
      fs.readFile( './static/fulian.jpg'.'binary'.function( error , data ) {
        if( error ) throw error 
        res.write( data, 'binary' )
        res.end()
      })
      break
    default: 
      break
   }

 }).listen( 8000.'localhost'.function () {
   console.log( 'Server running at: http://localhost:8000')})Copy the code

Static resource services

5.1 readStaticFile

/modules/readStaticFile.js

// Import dependent modules
var path = require('path')
var fs = require('fs')
var mime = require('mime')

function readStaticFile(res, filePathname) {

  var ext = path.parse(filePathname).ext
  var mimeType = mime.getType(ext)

  // Check whether the path has a suffix, if so, the client is requesting a file
  if (ext) {
    // Read the corresponding file according to the target file path passed in
    fs.readFile(filePathname, (err, data) = > {
    // Error handling
      if (err) {
        res.writeHead(404, { "Content-Type": "text/plain" })
        res.write("404 - NOT FOUND")
        res.end()
      } else {
        res.writeHead(200, { "Content-Type": mimeType })
        res.write(data)
        res.end()
      }
    });
    // Return true to indicate that the client wants a static file
    return true
  } else {
    // Returning false indicates that the client does not want a static file
    return false}}// Export the function
module.exports = readStaticFile
Copy the code

5.2 server

/server.js

// Introduce related modules
var http = require('http');
var url = require('url');
var path = require('path');
var readStaticFile = require('./modules/readStaticFile');

// Set up the HTTP server
var server = http.createServer(function(req, res) {
  var urlObj = url.parse(req.url);
  var urlPathname = urlObj.pathname;
  var filePathname = path.join(__dirname, "/public", urlPathname);

  // Read static files
  readStaticFile(res, filePathname);
});

// Listen for requests on port 3000
server.listen(3000.function() {
  console.log("Server running.");
  console.log("Listening on port 3000 :")})Copy the code

5.3 Final Directory Structure