Differences between module.export and exports
-
Fundamental difference:
exports returns module functions
module.exports returns the module object itself and a class -
The difference in use is:
The methods of exports can be called directly
module.exports can be called only after the new object is required -
Change direction:
If you change the direction of module.export, the direction of exports will be affected
Changing the direction of exports will not affect the direction of module.export -
Relationship:
Exports is a reference to module.exports, which refers to module.exports
It is found that console.log(exports === module.exports) returns true,
Description exports and module.exports are the same object
The loading of require is synchronous
If no suffix is specified during loading, it shall be executed in the following order:
- .js
- .json
- . node (module written in C/C + +)
main:app.js => index.js => index.json => index.node
<!- require('./a') ->
<!—— require(‘http’) lib node_modules - > go up one layer at a time until an error is reported if it is not found
express
characteristic:
1. The routing function is realized
2. Middleware (function) function
3. Extension of req and res objects
4. Other template engines can be integrated
Program on node.js
REPL introduction
- REPL full name: read Eval print loop (Interactive interpreter)
- R read - reads user input, parses the input Javascript data structure and stores it in memory.
- E execute - execute the data structure of the input
- P print - output results
- L cycle - cycle the above steps until the user presses the ctrl-c button twice to exit.
- Write the program in REPL (similar to the console function in the browser developer tool)
- Directly enter the node command on the console to enter the REPL environment
- Press Control + C twice to exit the REPL interface or enter. Exit to exit the REPL interface
- Hold down the control key and press the c key twice
Create a JavaScript file writer
JavaScript file name naming rules
- Don't use Chinese
- Do not include spaces
- Do not appear node keyword
- It is recommended to split words with '-'
case
- Case 1: write a simple function to add numbers
var n = 10; var m = 100; function add(x, y) { return x + y; } var result = add(m, n); console.log('The calculation result is:' + result);
- Case: file reading and writing case (take the students to open the official document for reference)
-
Used module var fs = require('fs');
-
1. Write file: fs.writeFile(file, data[, options], callback);
- Parameter 1: file path to write; required.
- Parameter 2: data to be written; required.
- Parameter 3: options when writing files, such as file code, optional.
- Parameter 4: callback function after file writing; required.
- Write file note:
- The operation is performed asynchronously
- If the file already exists, replace it
- The default write file code is utf8
- The callback function has one parameter: err, which indicates whether an error occurred during the operation of writing to the file.
- If something goes wrong err= Null, otherwise err === null
-
2. Read file: fs.readFile(file[, options], callback)
- Parameter 1: file path to read; required.
- Parameter 2: options when reading files, such as file encoding. Optional.
- Parameter 3: callback function after reading the file; required.
- Read the file note:
- The operation is performed asynchronously
- The callback function has two parameters, err and data
- If no encoding is specified when reading the file, the returned binary data will be native; If the encoding is specified, the corresponding string data will be returned according to the specified encoding.
-
be careful:
- The. / in the file operation indicates the current path, which is relative to the path of executing the node command, rather than the actual path of the currently executed *. js file.
- __ dirname always represents the actual path of the currently executed *. js file
- /Indicates the root directory. When reading or writing files, write / directory is equivalent to the current disk root directory under Windows (such as c: \ or d: \ or e: \ and hard disk root directory /) under Mac
// ---------------------------------Write file----------------------------- // Load file operation module var fs = require('fs'); // Creates a string for the file to write to var msg = 'Hello, world! Hello Node.js.'; // Perform a file write operation fs.writeFile('./data.txt', msg, 'utf8', function (err) { console.log('---' + err + '----'); // /Error determining whether to write file if (err) { console.log('File write error, detailed error information:' + err); // Continue to throw the error up throw err; } else { console.log('File written successfully!'); } }); // ---------------------------------Read file----------------------------- // Load file operation module var fs = require('fs'); // Perform a file read operation fs.readFile('./data.txt', 'utf8', function (err, data) { // Output err and data // console.log('error: ' + err); // console.log('data: ' + data); if (err) { console.log('Error reading file! detailed information: ' + err); } else { console.log('The file was read successfully. The following is the file content:'); console.log(data); } });
- Case 4: creating a catalog case
// Create a folder // Load file operation module var fs = require('fs'); // Create a directory fs.mkdir('./test-mkdir', function (err) { if (err) { console.log('Error creating directory, details are as follows:'); console.log(err); } else { console.log('Directory created successfully!'); } }); // ---------------------------------------------------------- // Load file operation module var fs = require('fs'); // 1. Create the '01 - teaching materials' directory fs.mkdir('./01-resources material', function (err) { if (err) { throw err; } // 1.1 create '01 - note outline' directory fs.mkdir('./01-resources material/01-Note outline'); // 1.2 create '02 - job tasks' directory fs.mkdir('./01-resources material/02-Job task'); // 1.3 create '03 material data' directory fs.mkdir('./01-resources material/03-Material data'); // 1.4 create '04 - Notes in class' directory fs.mkdir('./01-resources material/04-Notes in class'); }); // 2. Create the '02 source code' directory fs.mkdir('./02-source code', function (err) { if (err) { throw err; } // 2.1 create 'Preview code' directory fs.mkdir('./02-source code/Preview code'); // 2.2 create 'class code' directory fs.mkdir('./02-source code/Classroom code'); }); // 3. Create '03 video' directory fs.mkdir('./03-video'); // 4. Create the '04 - other data' directory fs.mkdir('./04-Other information');
be careful:
- Asynchronous operations cannot catch exceptions through try catch. You should judge whether there is an error by judging error.
- Synchronous operations can catch exceptions through try catch.
- Do not use fs.exists(path, callback) to judge whether the file exists, just judge error directly
- Path problem in file operation
- When reading and writing files, ". /" indicates the path where the node command is currently executed, not the path of the executed js file
- __ dirname, which always means "directory of js currently executed"
- __ filename, which means "the file name (including path) of the executed js"
- Error first introduction (error first)
Case 5: writing http service program through node.js - minimalist version
Steps:
- Load http module
- Create http service
- Add a request event handler for the http service object
- Enable http service listening and prepare to receive client requests
be careful:
-
The browser display may be garbled, so you can set the encoding used for browser display through res.setheader ('content type ',' text / plain; charset = UTF-8 ').
-
The Chrome browser cannot set the encoding manually by default, and the "Set Character Encoding" extension needs to be installed.
-
Demonstrate the difference between setting content type = text / HTML and content type = text / plain.
Reference code:
// 1. Load http module var http = require('http'); // 2. Create http service var server = http.createServer(); // 3. Start listening to the 'request' event server.on('request', function (req, res) { // body... console.log('Someone asked~~'); }); // 4. Start the service and start listening server.listen(9000, function () { console.log('The service has been started, please visit: http://localhost:9000'); });
Case 6: write http service program through node.js - make different responses according to different requests
explain:
- According to different requests, the index page, login page, register page and list page are displayed.
- Request / or / index
- Request / login
- Request / register
- Request / list
Reference code
// Load http module var http = require('http'); // Create http server var server = http.createServer(function (req, res) { // body... console.log(req.url); if (req.url === '/' || req.url === '/index') { // Indicates the request for the home page of the website res.end('This is index.html'); } else if (req.url === '/login') { // Indicates the requested login page res.end('This is login.html'); } else if (req.url === '/register') { // Indicates the request registration page res.end('This is register.html'); } else if (req.url === '/list') { // Represents a request list page res.end('This is list.html'); } else { // Indicates that the requested page does not exist res.writeHead(404, 'Not Found'); res.end('Sorry, page not found.'); } }); // Listen for network requests from ports server.listen(9000, function () { console.log('http://localhost:9000'); });
Case 7: writing http service program through node.js - responding to user requests by reading static HTML files
Steps:
- Create index.html, login.html, register.html, list.html, 404.html files.
- Demonstrates how to respond to users by reading the simplest HTML file.
- Demonstrates how to respond to users by reading an HTML file with an imported external CSS style sheet.
- Demonstrates how to respond to users by reading HTML files with img tags.
be careful:
-
1. Note: when sending different types of files, set the corresponding content type
-
2. HTTP status code reference
-
3. Write the meaning of relative path '. /' and absolute path '/' in the html page.
- This path in the web page is mainly used to tell the browser to which address to send the request
- '. /' indicates that the request starts from the request path relative to the current page (that is, the request path when the server returns to the current page)
- '/' indicates that the request starts from the root directory
Supplementary knowledge points:
- join() method of path module
Reference code:
// 1. Load http module var http = require('http'); // Load file operation module var fs = require('fs'); // Load the path module, which is mainly used to handle various paths. var path = require('path'); // 2. Create http server var server = http.createServer(function (req, res) { // 1. Get the URL requested by the user var url = req.url.toLowerCase(); // 2. Make different responses according to different requests of users if (url === '/' || url === '/index') { // Read the index.html file and respond to the user fs.readFile(path.join(__dirname, 'index.html'), function (err, data) { if (err) { throw err; } res.writeHead(200, 'OK', { 'Content-Type': 'text/html; charset=utf-8' }); // res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end(data); }); } else if (url === '/login') { // Read the login.html file and respond to the user fs.readFile(path.join(__dirname, 'login.html'), function (err, data) { if (err) { throw err; } res.writeHead(200, 'OK', { 'Content-Type': 'text/html; charset=utf-8' }); // res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end(data); }); } else if (url === '/register') { // Read the register.html file and respond to the user fs.readFile(path.join(__dirname, 'register.html'), function (err, data) { if (err) { throw err; } res.writeHead(200, 'OK', { 'Content-Type': 'text/html; charset=utf-8' }); // res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end(data); }); } else if (url === '/404') { // Read the register.html file and respond to the user fs.readFile(path.join(__dirname, '404.html'), function (err, data) { if (err) { throw err; } res.writeHead(200, 'OK', { 'Content-Type': 'text/html; charset=utf-8' }); // res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end(data); }); } }); // 3. Start service server.listen(9090, function () { // body... console.log('please visit: http://localhost:9090'); });
Case 8: simulate Apache to implement static resource server
Steps:
- Create a separate directory to implement, for example, create a "07 Apache" directory.
- Create a new public directory under this directory. It is assumed that this directory is a static resource directory.
- Find the resources under the corresponding path in the public directory according to the path requested by the user.
- If it is found, the resource is returned to the user. If it is not found, a 404 error is returned.
- Set the content type of different types of resources through the mime module
- After the implementation, copy 'An Ocean of Sky' and 'Hacker News' in the material to the static resource directory respectively, and test whether it is successful
other:
- Introducing NPM
- Introducing the mime third party module
- npm install mime
- Directly var mime = require('mime ') in code
Reference code:
// 1. Load the corresponding module // 1.1 loading http module var http = require('http'); // 1.2 load the path module to facilitate path splicing var path = require('path'); // 1.3 loading file reading module var fs = require('fs'); // 1.4 load the module to determine the MIME type of the file var mime = require('mime'); // 2. Create http server var server = http.createServer(); // 3. Listen to the user request event server.on('request', function (req, res) { // 1. Obtain the user's request path and convert it to lowercase var url = req.url.toLowerCase(); // Judge that if the requested path is' / ', it is equivalent to' / index.html ' url = (url === '/') ? '/index.html' : url; // 2. According to the url path requested by the user, go to the public directory to find the corresponding static resource file. Once found, read the file and return the result to the user // 2.1 splice the path of local resource file according to the url requested by the user var filePath = path.join(__dirname, 'public', url); // 2.2 set the content type according to the requested file path res.setHeader('Content-Type', mime.lookup(url)); // 2.2 read the corresponding file according to the path // [note] before reading the file, it is not necessary to judge whether the file already exists, but to judge whether the file is read successfully and the error occurs according to the error message in the callback function of reading the file fs.readFile(filePath, function (err, data) { // Determine whether there is an error if (err) { if (err.code === 'ENOENT') { // Determine whether the requested file does not exist res.setHeader('Content-Type', 'text/html; charset=utf8'); res.statusCode = 404; res.statusMessage = 'Not Found'; res.end('<h1>The requested resource does not exist!</h1>'); } else if (err.code === 'EACCES') { // Determine whether the file has access rights res.setHeader('Content-Type', 'text/html; charset=utf8'); res.statusCode = 403; res.statusMessage = 'Forbidden'; res.end('<h1>Permission denied!</h1>'); } else { throw err; } } else { // If there is no error, the read file is returned to the user res.statusCode = 200; res.statusMessage = 'OK'; res.end(data); } }) }); // 4. Start service server.listen(9000, function () { // body... console.log('server is running, please visit: http://localhost:9000'); });
Common System Errors - common error number
-
EACCES (Permission denied)
- An attempt was made to access a file in a way forbidden by its file access permissions.
- access was denied
-
EADDRINUSE (Address already in use)
- An attempt to bind a server (net, http, or https) to a local address failed due to another server on the local system already occupying that address.
- The address is in use (for example, the port number is occupied by standby)
-
EEXIST (File exists)
- An existing file was the target of an operation that required that the target not exist.
- file already exists
-
EISDIR (Is a directory)
- An operation expected a file, but the given pathname was a directory.
- The given path is a directory
-
ENOENT (No such file or directory)
- Commonly raised by fs operations to indicate that a component of the specified pathname does not exist – no entity (file or directory) could be found by the given path.
- The file or directory does not exist
-
ENOTDIR (Not a directory)
- A component of the given pathname existed, but was not a directory as expected. Commonly raised by fs.readdir.
- The given path is not a directory
Synchronous and asynchronous file operations
- fs.readFile(file[, options], callback)
- fs.readFileSync(file[, options])
The pop-up download function is realized by setting the http response message header
- Set content type: application / octet stream
- Set content disposition: attachment; filename=demo.txt