nodejs (Part III): nodejs files module, nodejs in require and exports, http module supplement, JavaScript Standard Style

A, nodejs files module

In nodejs, the user-written modules, called file module .

File module, refers js file, files or JSON .node file. In the path of the referenced file when the module you want to add files: /.../.../ xxx.js indicates an absolute path, / xxx.js represents the relative path (the same folder xxx.js) ,.. ./ indicate the parent directory. If neither plus nor /.../,../ plus ./, then either the module is the core module, either loaded from a node_modules file folder.

(1) In the Node.js, require a method, only to load script to perform multiple JavaScript files require methods.

Custom modules relative path must be written. / JS suffix may be omitted.

demo

In the same folder test, create a.js, b.js

Were written content

a.js content:

console.log('a start')
require('./b')
console.log('a end')

b.js content

console.log('b msg')

Execution a.js, output

ERROR: The process "node.exe" not found.
a start
b msg
a end
[Finished in 0.5s]

Analysis: require b.js in loading code, the code is executed in which

(2) require loading only executes the code, the module is isolated from the scope

Because it is between files and module scope (no concept of global scope in Node.js), the module is completely closed, unable to access the internal external, internal fan can not access external.

Test 1: Test value between file module affect each other or be covered

In the same folder test, create a.js, b.js

Were written content

a.js content:

var foo = 'aaa'
console.log('a start')
require('./b')
console.log('a end')
console.log('foo 的值是:', foo)

b.js content

console.log('b msg')
var foo = 'bbb'
console.log('b end')

Execution a.js, output

ERROR: The process "node.exe" not found.
a start
b msg
b end
a end
foo 的值是: aaa
[Finished in 0.4s]

Analysis: As can be seen from the output results b.js introduced between the module and does not affect the values ​​a.js foo, the file with the file scope is isolated from

Test 2: call the original file in the file module in the function module introduced in

In the same folder test, create a.js, b.js

Were written content

a.js content:


console.log('a start')

function add(x, y) {
  return x + y
}

require('./b')
console.log('a end')

b.js content

console.log('b msg')
console.log(add(10, 20))
console.log('b end')

Execution a.js, the output execution error, add is not defined, the function is not defined, the original file can not be referenced function module

Two, nodejs in exports and require

require

requireFunction is used to load and use other modules in the current module, passing in a module name, to return a module to export the object. Module may use a relative path name (in ./the beginning), or an absolute path ( /or C:the beginning of the letter or the like). Further, the module name .jsextension may be omitted. Here is an example.

There are two methods require action:

  1. Load the file and execute code inside the module
  2. Get the interface object is exported by the module load file
var foo1 = require('./foo');
var foo2 = require('./foo.js');
var foo3 = require('/home/user/foo');
var foo4 = require('/home/user/foo.js');

// foo1至foo4中保存的是同一个模块的导出对象。

In addition, you can load and use a JSON file using the following method.

var data = require('./data.json');

exports

exportsThe object is derived objects of the current module, and a method for deriving module public properties. Other modules by requireusing the current module is obtained when the current module function exportsobject. Deriving a public method of the following example.

In each file module provides an object: exports
exports default is an empty object
you need to do is to put all members need to be mounted external access to the exports object

exports.hello = function () {
    console.log('Hello World!');
};

test

In the same folder test, create a.js, b.js

Were written content

a.js content:

var bExports = require('./b') //引入b文件处理模块

console.log(bExports.foo) //从require对象中接收到foo属性的值

console.log(bExports.add(10, 30))//从require对象中接收到add函数

console.log(bExports.age)  //未能接收到age属性,所以输出值是undefined

bExports.readFile('./a.js')  //这里执行的是b.js的readFile函数,与fs模块中的
//readFile函数无关

console.log('------分割线-------')

var fs = require('fs')  //引入fs文件处理模块

fs.readFile('./a.js', function (err, data) {
	//执行fs模块的readFile方法
  if (err) {
    console.log('读取文件失败')
  } else {
    console.log(data.toString())
  }
})

b.js content

var foo = 'bbb'

// console.log(exports)

exports.foo = 'hello'

exports.add = function (x, y) {
  return x + y
}

exports.readFile = function (path, callback) {
  console.log('文件路径:', path)
}

var age = 18

// exports.age = age

function add(x, y) {
  return x - y
}

Execution a.js, output

ERROR: The process "node.exe" not found.
hello
40
undefined
文件路径: ./a.js
------分割线-------
var bExports = require('./b') //引入b文件处理模块

console.log(bExports.foo) //从require对象中接收到foo属性的值

console.log(bExports.add(10, 30))//从require对象中接收到add函数

console.log(bExports.age)  //未能接收到age属性,所以输出值是undefined

bExports.readFile('./a.js')  //这里执行的是b.js的readFile函数,与fs模块中的
//readFile函数无关

console.log('------分割线-------')

var fs = require('fs')  //引入fs文件处理模块

fs.readFile('./a.js', function (err, data) {
	//执行fs模块的readFile方法
  if (err) {
    console.log('读取文件失败')
  } else {
    console.log(data.toString())
  }
})

[Finished in 0.4s]

Analysis: a.js by bExports properties and functions by receiving b.js exports` mounted objects, the display is not undefined

Three, http module supplements

Setting response header

res.setHeader ()

var http = require('http')

var server = http.createServer()

server.on('request', function (req, res) {
  // 在服务端默认发送的数据,其实是 utf8 编码的内容
  // 但是浏览器不知道你是 utf8 编码的内容
  // 浏览器在不知道服务器响应内容的编码的情况下会按照当前操作系统的默认编码去解析
  // 中文操作系统默认是 gbk
  // 解决方法就是正确的告诉浏览器我给你发送的内容是什么编码的
  // 在 http 协议中,Content-Type 就是用来告知对方我给你发送的数据内容是什么类型
  // res.setHeader('Content-Type', 'text/plain; charset=utf-8')
  // res.end('hello 世界')

  var url = req.url

  if (url === '/plain') {
    // text/plain 就是普通文本
    res.setHeader('Content-Type', 'text/plain; charset=utf-8')
    //设置响应头
    res.end('hello 世界')
  } else if (url === '/html') {
    // 如果你发送的是 html 格式的字符串,则也要告诉浏览器我给你发送是 text/html 格式的内容
    res.setHeader('Content-Type', 'text/html; charset=utf-8')
    res.end('<p>hello html <a href="">点我</a></p>')
  }
})

server.listen(3000, function () {
  console.log('Server is running...')
})

fs module in conjunction with http module

Send a file over a network (http binding fs transmission data file): file is not transmitted, are transmitted on the nature of the content file, when the browser receives the server response content, the correspondence will be parsed as Content-Type deal with

// 1. 结合 fs 发送文件中的数据
// 2. Content-Type
//    http://tool.oschina.net/commons
//    不同的资源对应的 Content-Type 是不一样的
//    图片不需要指定编码
//    一般只为字符数据才指定编码

var http = require('http')
var fs = require('fs')

var server = http.createServer()

server.on('request', function (req, res) {
  // / index.html
  var url = req.url

  if (url === '/') {
    // 肯定不这么干
    // res.end('<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><h1>首页</h1></body>/html>')

    // 我们要发送的还是在文件中的内容
    fs.readFile('./resource/index.html', function (err, data) {
      if (err) {
        res.setHeader('Content-Type', 'text/plain; charset=utf-8')
        res.end('文件读取失败,请稍后重试!')
      } else {
        // data 默认是二进制数据,可以通过 .toString 转为咱们能识别的字符串
        // res.end() 支持两种数据类型,一种是二进制,一种是字符串
        res.setHeader('Content-Type', 'text/html; charset=utf-8')
        res.end(data)
      }
    })
  } else if (url === '/xiaoming') {
    // url:统一资源定位符
    // 一个 url 最终其实是要对应到一个资源的
    fs.readFile('./resource/ab2.jpg', function (err, data) {
      if (err) {
        res.setHeader('Content-Type', 'text/plain; charset=utf-8')
        res.end('文件读取失败,请稍后重试!')
      } else {
        // data 默认是二进制数据,可以通过 .toString 转为咱们能识别的字符串
        // res.end() 支持两种数据类型,一种是二进制,一种是字符串
        // 图片就不需要指定编码了,因为我们常说的编码一般指的是:字符编码
        res.setHeader('Content-Type', 'image/jpeg')
        res.end(data)
      }
    })
  }
})

server.listen(3000, function () {
  console.log('Server is running...')
})

Four, JavaScript Standard Style (Js standard coding style)

使用两个空格 – 进行缩进

字符串使用单引号 – 需要转义的地方除外

不再有冗余的变量 – 这是导致 大量 bug 的源头!

行首不要以 (, [, or ` 开头

这是省略分号时唯一会造成问题的地方 – 工具里已加了自动检测!

关键字后加空格 if (condition) { ... }

函数名后加空格 function name (arg) { ... }

坚持使用全等 === 摒弃 == 一但在需要检查 null || undefined 时可以使用 obj == null。

一定要处理 Node.js 中错误回调传递进来的 err 参数。

使用浏览器全局变量时加上 window 前缀 – document 和 navigator 除外

避免无意中使用到了这些命名看上去很普通的全局变量, open, length, event 还有 name。



// 当你采用了无分号的代码风格的时候,只需要注意以下情况就不会有上面的问题了:
//    当一行代码是以:
//        (
//        [
//        `
//        开头的时候,则在前面补上一个分号用以避免一些语法解析错误。
//    所以你会发现在一些第三方的代码中能看到一上来就以一个 ; 开头。
//  结论:
//    无论你的代码是否有分号,都建议如果一行代码是以 (、[、` 开头的,则最好都在其前面补上一个分号。
//    有些人也喜欢玩儿一些花哨的东西,例如可以使用 ! ~ 等。

Conditions

  • Use two spaces to indent
function hello (name) {
  console.log('hi', name)
}
  • Except as required escaped, strings unified single quotes
console.log('hello there')
$("<div class='box'>")
  • Do not leave unused variables
function myFunction () {
  var result = something()   // ✗ avoid
}
  • The keyword spaces
if (condition) { ... }   // ✓ ok
if(condition) { ... }    // ✗ avoid
  • When the function is declared between the parentheses of the function name spaces
function name (arg) { ... }   // ✓ ok
function name(arg) { ... }    // ✗ avoid

run(function () { ... })      // ✓ ok
run(function() { ... })       // ✗ avoid
  • Always use alternative == ===

Exception: obj == nullit can be used to checknull || undefined

if (name === 'John')   // ✓ ok
if (name == 'John')    // ✗ avoid

if (name !== 'John')   // ✓ ok
if (name != 'John')    // ✗ avoid
  • String concatenation operator (Infix operators) to leave a space between the
// ✓ ok
var x = 2
var message = 'hello, ' + name + '!'

// ✗ avoid
var x=2
var message = 'hello, '+name+'!'
  • Behind the comma and space
// ✓ ok
var list = [1, 2, 3, 4]
function greet (name, options) { ... }

// ✗ avoid
var list = [1,2,3,4]
function greet (name,options) { ... }
  • else the keywords you want to keep the brace on the same line
// ✓ ok
if (condition) {
  // ...
} else {
  // ...
}

// ✗ avoid
if (condition) {
  // ...
}
else {
  // ...
}
  • Multi-line if statement brackets should not be spared
// ✓ ok
if (options.quiet !== true) console.log('done')

// ✓ ok
if (options.quiet !== true) {
  console.log('done')
}

// ✗ avoid
if (options.quiet !== true)
  console.log('done')
  • Plus window. Prefix when using global variables browser

Exception: document, console,navigator

window.alert('hi')   // ✓ ok
  • It does not allow multi-line continuous blank lines
// ✓ ok
var value = 'hello world'
console.log(value)
// ✗ avoid
var value = 'hello world'


console.log(value)
  • And for the ternary operator:? Code with which they are responsible in the same row
// ✓ ok
var location = env.development ? 'localhost' : 'www.api.com'

// ✓ ok
var location = env.development
  ? 'localhost'
  : 'www.api.com'

// ✗ avoid
var location = env.development ?
  'localhost' :
  'www.api.com'
  • Each var keyword alone declare a variable
// ✓ ok
var silent = true
var verbose = true

// ✗ avoid
var silent = true, verbose = true

// ✗ avoid
var silent = true,
    verbose = true
  • Spaces on both sides of a single line of code blocks
function foo () {return true}    // ✗ avoid
function foo () { return true }  // ✓ ok
  • For variable and function names use camel unified nomenclature
function my_function () { }    // ✗ avoid
function myFunction () { }     // ✓ ok

var my_var = 'hello'           // ✗ avoid
var myVar = 'hello'            // ✓ ok
  • End of the line does not allow extra comma
var obj = {
  message: 'hello',   // ✗ avoid
}
  • Always put a comma end of the line
var obj = {
  foo: 'foo'
  ,bar: 'bar'   // ✗ avoid
}

var obj = {
  foo: 'foo',
  bar: 'bar'   // ✓ ok
}
  • Dot operator must be within the same line with the properties
  console.
    log('hello')  // ✗ avoid

  console
    .log('hello') // ✓ ok
  • Leave a blank line at the end of file

  • When the function call without leaving a gap between the identifier and the brackets

console.log ('hello') // ✗ avoid
console.log('hello')  // ✓ ok
  • Among key-value pairs between the colon and the value to be left blank
var obj = { 'key' : 'value' }    // ✗ avoid
var obj = { 'key' :'value' }     // ✗ avoid
var obj = { 'key':'value' }      // ✗ avoid
var obj = { 'key': 'value' }     // ✓ ok
  • The constructor should begin with a capital letter
function animal () {}
var dog = new animal()    // ✗ avoid

function Animal () {}
var dog = new Animal()    // ✓ ok
  • Instead of using the array literal constructor
var nums = new Array(1, 2, 3)   // ✗ avoid
var nums = [1, 2, 3]            // ✓ ok
  • Avoid using modified variables declared const
const score = 100
score = 125       // ✗ avoid
  • Avoiding the use of a constant as a condition of the conditional expression (excluding loop)
if (false) {    // ✗ avoid
  // ...
}

if (x === 0) {  // ✓ ok
  // ...
}

while (true) {  // ✓ ok
  // ...
}
  • When finished disposable module has a plurality of same introduction
import { myFunc1 } from 'module'
import { myFunc2 } from 'module'          // ✗ avoid

import { myFunc1, myFunc2 } from 'module' // ✓ ok
  • Do not extend native objects
Object.prototype.age = 21     // ✗ avoid
  • Be sure to use the break to switch to interrupt normal conditional branch
switch (filter) {
  case 1:
    doSomething()    // ✗ avoid
  case 2:
    doSomethingElse()
}

switch (filter) {
  case 1:
    doSomething()
    break           // ✓ ok
  case 2:
    doSomethingElse()
}

switch (filter) {
  case 1:
    doSomething()
    // fallthrough  // ✓ ok
  case 2:
    doSomethingElse()
}
  • Do not re-assignment to a global read-only objects
window = {}     // ✗ avoid
  • Do not mix spaces and tabs as indents

  • In addition to indent Do not use multiple spaces

const id =    1234    // ✗ avoid
const id = 1234       // ✓ ok
  • Assigned to the variable needs to create the new object instance
new Character()                     // ✗ avoid
const character = new Character()   // ✓ ok
  • Prohibit the use of the Function constructor
var sum = new Function('a', 'b', 'return a + b')    // ✗ avoid
  • Prohibit the use of Object constructor
let config = new Object()   // ✗ avoid
  • Avoid the use of string splicing and __filename __dirname
const pathToFile = __dirname + '/app.js'            // ✗ avoid
const pathToFile = path.join(__dirname, 'app.js')   // ✓ ok
  • Do not repeat declare variables
let name = 'John'
let name = 'Jane'     // ✗ avoid

let name = 'John'
name = 'Jane'         // ✓ ok
  • Assignment return statement must have wrapped brackets
function sum (a, b) {
  return result = a + b     // ✗ avoid
}

function sum (a, b) {
  return (result = a + b)   // ✓ ok
}
  • return, behind these statements throw, continue and break the code is redundant
function doSomething () {
  return true
  console.log('never called')     // ✗ avoid
}
  • Do not stay between the operator and expanded its blank expression
fn(... args)    // ✗ avoid
fn(...args)     // ✓ ok
  • In front of the semicolon with no spaces, spaces left behind
for (let i = 0 ;i < items.length ;i++) {...}    // ✗ avoid
for (let i = 0; i < items.length; i++) {...}    // ✓ ok
  • Leave a space before the code block begins
if (admin){...}     // ✗ avoid
if (admin) {...}    // ✓ ok
  • Without leaving spaces between parentheses
getName( name )     // ✗ avoid
getName(name)       // ✓ ok
  • Leave a space before and after comments
//comment           // ✗ avoid
// comment          // ✓ ok

/*comment*/         // ✗ avoid
/* comment */       // ✓ ok
  • No spaces before and after the template variable string
const message = `Hello, ${ name }`    // ✗ avoid
const message = `Hello, ${name}`      // ✓ ok
  • NaN check the correct posture is to use the isNaN ()
if (price === NaN) { }      // ✗ avoid
if (isNaN(price)) { }       // ✓ ok

About semicolon

  • Do not use a semicolon
window.alert('hi')   // ✓ ok
window.alert('hi');  // ✗ avoid
  • Do not use the (, [, or and other `` `beginning of the line. Under no circumstances will lead to a semicolon after the error code compression, and adhere to this norm can avoid making mistakes.
// ✓ ok
;(function () {
  window.alert('ok')
}())

// ✗ avoid
(function () {
  window.alert('ok')
}())
// ✓ ok
;[1, 2, 3].forEach(bar)

// ✗ avoid
[1, 2, 3].forEach(bar)
// ✓ ok
;`hello`.indexOf('o')

// ✗ avoid
`hello`.indexOf('o')

The above wording only say too clever by half

such as:

;[1, 2, 3].forEach(bar)

The proposed wording is:

var nums = [1, 2, 3]
nums.forEach(bar)

Reference material

[1]https://www.jianshu.com/p/e889069b7c27

[2]https://github.com/standard/standard/blob/master/docs/RULES-zhcn.md

Guess you like

Origin www.cnblogs.com/Nicholas0707/p/12571457.html
Recommended