global
The browser’s global object is Window, whereas Node’s global object is Global. Global can be accessed directly from Node. The default declared properties are not placed on global because Node has an anonymous function wrapped around each module, i.e. this === module.exports
/ / exports require __dirname __filename. / / exports require __dirname __filename.
// Get the contents of global (function(){
console.log(Object.keys(this))
})()
Copy the code
process
- process.argv
By default, the first two parameters passed on behalf of the user through the Node execution file are meaningless
// node index.js --port = 3000 --config = 'xxx'Console. log(process.argv.slice(2)) // gets the method to pass the argumentlet config = process.argv.slice(2).reduce((memo,current,index,array)=>{
if(current.includes(The '-')){
memo[current.slice(2)] = array[index+1];
}
returnmemo; }, {});Copy the code
You can use Commander to parse process.argv and generate CLI-like command help, etc.
const program = require('commander');
const chalk = require('chalk'); // Parses the user's parameters by default --help program // configuration commands I enter the command to do something. Command ('create')
.alias('c')
.description('create project')
.action(()=>{
console.log('create project'}) program // Configure attributes to pass parameters to code. Option ('-p, --port <val>'.'set port')
.version('1.0.0')
program.on('--help',()=>{
console.log('\r\nExamples')
console.log(' node 1.js --help');
console.log(' node 1.js create '+chalk.green('project')) }).parse(process.argv); // chalk console.log(program.port);Copy the code
- process.chdir
The node.js method changes the current working directory of the node.js process, and raises an exception if the change fails
- process.cwd()
Returns the current working directory of the Node.js process. Where do I execute this file, the directory is the directory of the file that I’m executing, right
- Process.nexttick (microtask in Node)
Define an action and let it be executed at the time of the next event polling
- process.env
The environment variable can be executed differently depending on the value of the variable. Windows and MAC can set this variable differently. You can use cross-env to set this variable.
CommonJS specification and implementation
Implementation steps
- The req method passes the file path, and module. resolveFileName resolves to an absolute path
- Determine the cache, there is direct use, there is no create a new module, and then add to the cache
- The module loads module.load and returns module.exports
- Different methods are adopted according to different file name suffixes
- The JSON file is returned directly, the JS file is wrapped in a closure and then executed using the vm.runInThisContext generator
const path = require("path");
const fs = require("fs");
const vm = require("vm");
functionModule(id) { this.id = id; this.exports = {}; } module.wrapper = ["(function(module,exports,require,__filename,__dirname){"."})"
];
Module.extensions = {
".js"(module) {
let script = fs.readFileSync(module.id, "utf8");
let fnStr = Module.wrapper[0] + script + Module.wrapper[1];
letfn = vm.runInThisContext(fnStr); Exports fn. Call (module.exports, module, module.exports, req, module.id, req, module. path.dirname(module.id) ); // exports has been changed by the user}, // js needs to pass exports to the user".json"(module) {// Node is assigned by default after parsinglet script = fs.readFileSync(module.id, "utf8"); module.exports = JSON.parse(script); }}; // Give you a relative path to resolve into an absolute path module.resolvefilename =function(filename) {// 1) By default, a relative path is converted to an absolute pathlet absPath = path.resolve(__dirname, filename);
letflag = fs.existsSync(absPath); // Determine whether the file has an asynchronous method discardedletcurrent = absPath; // The default is the current pathif(! flag) {let keys = Object.keys(Module.extensions);
for (leti = 0; i < keys.length; i++) { current = absPath + keys[i]; // The path of the currently found filelet flag = fs.existsSync(current);
if (flag) {
break;
} else{ current = null; }}}if(! Current) {// Throw new Error("File does not exist");
}
returncurrent; // Return file path}; Module.prototype.load =function() {// Module loading is to read the contents of the fileletext = path.extname(this.id); Module.extensions[ext](this); // call different processing methods according to different suffixes}; Module.cache = {};functionReq (filename) {// implements a require methodlet current = Module.resolveFileName(filename);
if (Module.cache[current]) {
return Module.cache[current].exports;
}
letmodule = new Module(current); Cache [current] = module; module.load();returnmodule.exports; // exports module.exports object}Copy the code