Node.js is a development platform, with the corresponding programming language (JS), runtime environment (Chrome V8), provides specific functions of the API, can develop console applications, desktop applications, Web applications.
The ecosystem is NPM, which is event-driven, non-blocking I/O(asynchronous callback), single-threaded.
English official website :nodejs.org/en/ can be switched to Chinese (right side of the website)
Chinese API documentation:nodejs.cn/api/
Global modules do not require require, and there are two ways to distinguish them
- See the documentation for the use case
- By looking at “global variables”
The API has three stability flags
-
Deprecated 0. This feature may trigger a warning. Backward compatibility is not guaranteed.
-
Experiment 1. This feature is not constrained by semantic versioning specifications. Backward incompatible changes or removals may occur in any future release. Do not use this feature in the production environment.
-
2. Compatibility with the NPM ecosystem is the highest priority.
const fs = require('fs');
fs.readFile("./hello.txt");
Copy the code
TXT is a relative path, which is searched according to the path where the node command is executed.
For example, the above file is in :D:\software\ hell.js, but on disk D, run Node software\ hell.js and it will be D:\ hell.txt
__dirname, which indicates the directory of the currently executing JS file, is not global.
__filename adds the filename to __dirname and is not global.
Try-catch can only catch synchronous operations, not asynchronous callbacks
const fs = require('fs'); Try {fs.readFile(' non-existent path ', (error) => {console.log(' readFile ', error. }); } catch (error) {console.log(' error caught ', error); }Copy the code
Output “Read file ENOENT”
Require loading modules are executed synchronously and are loaded sequentially
Relative paths always refer to the path of the current file
Js, index.json, and index.node. If there is no directory with the same name, it will be loaded as a third party module. If the path does not exist, load the index.js, index.json, and index.node files in the current folder again
If it is a module, look in the core module first. If it is not a module, consider it a third party module. Look for node_moudles in the current js file directory until the root directory
Pay attention to their own file name or path, do not and the system built-in module name.
The globally installed module NPM installs MIME -g, which you can try (some modules can only run in a browser environment) by calling from the command line