Node.js study notes (1) modular core modules +

In Node, the use of ES programming without the DOM, the BOM (Document, window), Node partial bottom

Terms of Use:

  1. String single quotes ''
  2. Keyword, function name spaces
  3. Use ===
  4. To err deal
  5. Except for the prefix plus the window, document and navigator when using global variables browser
  6. When the line of code is to ([ `the beginning of time, before the three sign a semicolon
    when Backticks ES6 in the new template string that supports wrapping and stitching variables

Core Module

FS (File System) core module (file operation function)

fs (file system) core module, provides an API for all file operations

  1. Require the use of load fs core module var fs = require('fs')
  2. Read File fs.readFile('a.txt ',function(err,data){console.log(data.toString());})Reference 1: read file path, reference 2: callback function can be used data.toString ()
  3. Write filefs.writeFile('a.txt','nihao',function(error){console.log("写入成功!");})

http core modules (created write server)

  1. Http kernel module is loaded var http = require('http')
  2. Use http.creatServer () to create a Web server , a server instance is returnedvar server = http.creatServer()
  3. Effect server: serving for data retransmission request, receives the request, processing the request, the response request server.on('request',function(req,res){})
    REQUEST request event handler, there are two parameters:. A request request object: to obtain a number of requests client information, such as request path
    b . response in response to: sending response information

Address: req.socket.remoteAddress
port number: req.socket.remotePort
IP address used to locate the computer, the port number used to locate a specific application
port number at the same time can only be occupied by a program, but the computer can open multiple simultaneous the service
server is a content default data transmission utf-8 encoded may be encoded with the default operating system is not the same
response.setHeader ( 'inform the data type', 'text / plain general text type, html using text / html; charset = utf-8 ') [HTML page may be a meta]

server.on("request",function(req,res){
	console.log("收到客户端请求,请求路径:"+req.url)
	console.log("地址:",req.socket.remoteAddress,req.socket.remotePort)
	var url = request.url
	if(url === '/'){
        fs.readFile('./htmla/a.html',function(err,data){
        if(err){
                response.setHeader('Content-Type','text/plain;charset=utf-8')
                response.end('文件读取失败,请稍后重试!')
            }else{
                response.setHeader('Content-Type','text/html;charset=utf-8')
                response.end(data)
            }
        })
})
  1. Start the server , bind the port number (network traffic)server.listen(3000,function(){console.log(3000,running...})
  2. Close using crtl + C

os core module

  1. Os kernel module is loaded var os= require('os')
  2. console.log(os.cpus()) It returns an array of objects, which contains information about each logical CPU core.
  3. console.log(os.totalmem()) Returns the total amount of system memory as an integer (in bytes).

path core module

  1. The core module load path var path= require('path')
  2. ` path.extname(‘index.html’)`` // Returns: ‘.html’
  3. path.basename('/foo/bar/baz/asdf/quux.html'); // Returns: ‘quux.html’
  4. path.dirname('/foo/bar/baz/asdf/quux'); // Returns: ‘/foo/bar/baz/asdf’
  5. path.parse('/home/user/dir/file.txt') // Returns: {root:’/’,dir:’/home/uesr/dir’,base:‘file.txt’,ext:’.txt’,name:‘file’}
  6. path.join('/foo','bar','baz/sa','..') // Returns '/ foo / bar / baz / in'

Other members of Node: in each module in addition require, exports and other modules related API, there are two special members

  1. __dirname: used to obtain the current file directory module belongs to the absolute path
  2. __filename: used to obtain the current file absolute path of the
    file operation, a relative path is not reliable, the path to the file operation is designed as a path (relative path) with respect to which the command execution node
    Solution: relative path into a dynamic absolute path (using __dirname / __ filename)path.join(__dirname,'./a.txt')

Note: the path identified by the path identifier and the module file operation is not the same, the path identity module is relative to the current file module , a path which is not affected node command execution.

Modular

What is modular?

  1. File scope ( only module scope , there is no global scope)
  2. Communication rule ( use require to load the module, used to derive the members exports interface object module )

Simple, modular (preferentially loaded from the cache)

There are three modules require load.

  1. User-written file module, using a relative path, add ./ current directory (not province) ... / upper-level directory require('./a') or require(''./a.js)
    thinking? How to enable communication between the module and the module.
    Each file module exports the object provides a default null {}

In b.js file:

var foo = 'a'
exports.foo = 'b'
console.log(exports)   // Returns : { foo: 'b' }

In a.js file:

var  aExports = require('./b')
console.log(aExports)   // Returns : { foo: 'b' }
console.log(aExports.foo)  // Returns : b

Thoughts? How to use exports to export multiple members (must be in the subject)?

var foo = 'a'
exports.foo = 'b'
exports.a = 123
exports.b  = function(){}
console.log(exports)

If a module needs to export directly to a member, it is to get the function / string, rather than mount a way to use module.exports

In Node, each module has its own internal target module var module = {}
of the module object has a member: exports, the default code of the last sentence there return module.exports
Note: module is an object, exports are objects

var module = {
	export:{}
}
var foo = 'a'
function add(x,y) {
    return x+y
}
exports = add
exports.foo = 'abc'
exports.a = '123'     // Return:{}

Not a single loading function with exports, the function must be used to load module.exports

var foo = 'a'
function add(x,y) {
    return x+y
}
module.exports = add
module.exports.foo = 'abc'
module.exports.a = '123  // Return : [Function: add] { foo: 'abc', a: '123' }

var a = aExports(1,2)
console.log(a)  // Retuen: 3
About paths
  1. A relative path of the file operation may be omitted ./data/a.txt, data/a.txt, /data/a.txtrelative to the current directory
  2. Loading module, the relative path can not be omitted ./
Released four original articles · won praise 3 · views 85

Guess you like

Origin blog.csdn.net/fAng_ER_/article/details/104037595