Nodejs introduction?
- Liverpoolfc.tv: Nodejs
- Provides a runtime that allows JS to run on the server
- The bottom layer of Node is written in c++
- Based on the JS V8 kernel, Node has formed a system-level API file operation and network programming to achieve its own Web services
- Node is an implementation of the CommonJS specification
Characteristics of the Node
- Event-driven: Node’s API is event-based and asynchronous
- Node is single-threaded (a limitation of the JS language), with only one main thread, but Node can start multiple processes
- Node is good for handling I/O intensive (file reads and writes)
- Not suitable for CPU-intensive service scenarios that require a lot of computing
Application scenarios
- Front and back end separation, integration of back-end interface, do the middle layer
- Write some tool library Webpack, CLI
Module loading in Node
Benefits of modularity
- 1. Can help us solve the problem of naming conflicts (each file will be wrapped around a function)
- 2. High cohesion and low coupling
Nodejs module loading principle
- By default, a layer of functions is added to the file during execution
- It’s passed in as an argument to a function that we can access directly in a file
The contents are wrapped in a self-executing function by reading the contents of the file. Module.exports is returned as a result by default
let a = `function (exports, require, module, __filename, __dirname) {
let a = 1
module.exports = 'hello';
return module.exports;
}(exports, require, module, xxxx, xxx)`
Copy the code
Modules in Node can be divided into three categories
- 1. The core module/built-in module FS HTTP path does not need to be installed. The relative path and absolute path do not need to be added
- 2. The third party module require(‘co’) needs to be installed, written by someone else
- 3. Import a user-defined module through an absolute path or a relative path
- 4. Third party modules, install first, look for the order of local directory -> higher directory… -> To the root directory
const fs = require("fs"); const path = require("path"); const a = require("a"); console.log(a); If (true) {const fs = require("fs"); const fs = require("fs"); }Copy the code
Circular references to modules
Node core module
Global process,
// 1. Attributes on global are global and do not need to be imported
console.log(Object.keys(global));
global.a = 1000;
console.log(a);
console.log(__dirname);
console.log(__filename);
/ / 2, - process -- -- -- -- -- -
console.log(Object.keys(process));
/ / the node version
console.log(process.version);
// Win32 Darwin
console.log(process.platform);
// set export
console.log(process.env);
console.log(process.env.NODE_ENV);
/ / / / parametersAs the key -console.log(process.argv);
console.log(process.pid);
console.log(process.cwd());
Promise.resolve().then(() = > {
console.log("Promise");
});
process.nextTick(() = > {
console.log("nextTick");
});
Copy the code
Fs – File read and write
const fs = require("fs"); const path = require("path"); // fs fileSystem allows you to manipulate the file directory.... // path.resolve path.join const absPath = path.resolve(__dirname, "note.md"); // Const data = fs.readFileSync(absPath); console.log(data.toString()); Error first fs.readFile(absPath, (err, data) => {if (err) {console.log(err); // Node API convention Error first fs.readFile(absPath, (err, data) => {if (err) {console.log(err); return; } console.log(data.toString()); }); const newFile = path.resolve(__dirname, "test.txt"); Fs. writeFile(newFile, "Hello world", {flag: "w"}, (err, data) => {if (! Err) {console.log(" write succeeded "); }}); // fs.appendfile is equivalent to the aboveCopy the code
HTTP – Web services
- server.js
const http = require("http");
// Js is single-threaded and node is single-threaded
let server = http.createServer((req, res) = > {
res.end(`{"code": 0}`);
});
// Port number to listen for requests
server.listen(3100.() = > {
console.log("server start");
});
Copy the code
- client.js
const http = require("http");
http.get("http://localhost:3100".res= > {
let rawData = "";
res.on("data".chunk= > {
rawData += chunk;
});
res.on("end".() = > {
try {
const parsedData = JSON.parse(rawData);
console.log("parsedData", parsedData);
} catch (e) {
console.error(e.message); }}); });Copy the code
Events – Event processing
let EventEmitter = require("events");
class MyEvent extends EventEmitter {}
const e = new MyEvent();
e.on("add", num => {
console.log("add", num);
});
e.emit("add", 12, 12, 122);
e.emit("add", 1);
e.once("min", () => {
console.log("once");
});
e.emit("min");
e.emit("min");
e.emit("min");
Copy the code
Buffer – the data flow
// const b1 = buffer. from("hello"); console.log(b1); // const b2 = Buffer. From (" hello ", "utf8"); console.log(b2); console.log(b2.toString()); console.log(b2.toString("hex")); // Base64 encoding will be 1/3 larger console.log(b2.tostring ("base64")); const b3 = Buffer.alloc(10); console.log(b3.toString("hex")); // // concatenate const b4 = buffer. concat([b1, b2]); console.log(b4.toString());Copy the code
Path-path processing
const path = require("path"); Let r = path.join(__dirname, "a", "b", "c", "/"); / / stitching can join together / / / let r1 = path. Resolve (__dirname, "a", "b", "c", "/"); Let ext = path.extname("a.min.js"); // let basename = path.basename("a.min.js", ".js"); // console.log(ext, basename); console.log(basename);Copy the code
Transfer code
Implement a static file Web service based on Node core module
const http = require("http");
const path = require("path");
const url = require("url");
const fs = require("fs");
const mime = require("mime");
function notFound(res) {
res.statusCode = 404;
res.end("Not Found");
}
let server = http.createServer((req, res) = > {
let { pathname, query } = url.parse(req.url, true);
const absPath = path.join(__dirname, pathname);
// I need to check if the path is a directory. If it is a directory, the default is to look for index.html
fs.stat(absPath, function (err, statObj) {
if (err) return notFound(res);
if (statObj.isFile()) {
fs.readFile(absPath, function (err, data) {
if (err) return notFound(res);
res.setHeader("Content-Type", mime.getType(absPath) + "; charset=utf-8");
res.end(data);
});
} else {
// see if there is index. HTML if there is, I'll return it
fs.readFile(path.join(absPath, "index.html"), function (err, data) {
if (err) return notFound(res);
res.setHeader("Content-Type"."text/html; charset=utf-8"); res.end(data); }); }}); }); server.listen(3000);
Copy the code
Express Framework Introduction
- Liverpoolfc.tv: Express
Express easy to use
// Express is a function
let express = require("./express");
// Generate an application with Express execution
let app = express();
// When the request comes in the same path and method will trigger the corresponding function
// Req and res are both native node req and res
app.get("/hello".function (req, res) {
res.end("hello");
});
app.listen(3000);
Copy the code
Express static file service
app.use(express.static("public"));
Copy the code
app.route(path)
app
.route("/events")
.all(function (req, res, next) {
// runs for all HTTP verbs first
// think of it as route specific middleware!
})
.get(function (req, res, next) {
res.json({});
})
.post(function (req, res, next) {
// maybe add a new event...
});
Copy the code