zoukankan      html  css  js  c++  java
  • Node.js 初心

    官方文档

    https://nodejs.org/dist/latest-v12.x/docs/api/

    非官方中文网

    http://nodejs.cn/
    http://nodejs.cn/api/

    安装Node.js

    使用snapd安装,非常方便。参考上一篇安装Vue-CLI教程。
    通过snapd安装Node.js最好执行一步额外的操作,这是snap特殊的启动脚本造成的:

    npm config set scripts-prepend-node-path true
    

    正如上一篇教程所做的那样,如果不配置scripts-prepend-node-path为true,很多时候都要添加一个--scripts-prepend-node-path参数,非常麻烦。

    初始化项目

    mkdir example-project
    cd example-project
    npm init -y
    

    产生一个package.json,大致如下,其中scripts是npm run $script的自定义集合:

    {
      "name": "hello",
      "version": "1.0.0",
      "description": "我的第一个Node.js程序",
      "main": "app.js",
      "scripts": {
        "test": "node app.js"
      },
      "author": "",
      "license": "ISC"
    }
    

    现在编辑文件app.js,开始写入我们的第一个Node.js项目代码

    const http = require("http")
    const config = { 
            host: "0.0.0.0",
            port: 80, 
    }
    
    const server = http.createServer((req, res) => {
            let values = []
            for (key in req) {
                    vars.push(key)
            }   
            console.log(values)
            res.write("<h1>Hello, Node.js</h1>")
            res.end()
    })
    
    server.listen(config.port, config.host, error => {
            console.log(`HTTP Server starting on ${config.host}:${config.port}`)
    })
    

    执行npm run test,访问服务器!

    $ curl localhost -v
    * Rebuilt URL to: localhost/
    *   Trying 127.0.0.1...
    * TCP_NODELAY set
    * Connected to localhost (127.0.0.1) port 80 (#0)
    > GET / HTTP/1.1
    > Host: localhost
    > User-Agent: curl/7.58.0
    > Accept: */*
    >
    < HTTP/1.1 200 OK
    < Date: Mon, 09 Dec 2019 13:40:00 GMT
    < Connection: keep-alive
    < Transfer-Encoding: chunked
    <
    * Connection #0 to host localhost left intact
    

    在npm后台可以看到

    HTTP Server starting on 0.0.0.0:80
    [
      '_readableState',      'readable',         '_events',
      '_eventsCount',        '_maxListeners',    'socket',
      'httpVersionMajor',    'httpVersionMinor', 'httpVersion',
      'complete',            'headers',          'rawHeaders',
      'trailers',            'rawTrailers',      'aborted',
      'upgrade',             'url',              'method',
      'statusCode',          'statusMessage',    'client',
      '_consuming',          '_dumped',          'setTimeout',
      '_read',               'destroy',          '_addHeaderLines',
      '_addHeaderLine',      '_dump',            '_undestroy',
      '_destroy',            'push',             'unshift',
      'isPaused',            'setEncoding',      'read',
      'pipe',                'unpipe',           'on',
      'addListener',         'removeListener',   'off',
      'removeAllListeners',  'resume',           'pause',
      'wrap',                'setMaxListeners',  'getMaxListeners',
      'emit',                'prependListener',  'once',
      'prependOnceListener', 'listeners',        'rawListeners',
      'listenerCount',       'eventNames'
    ]
    

    这些都是request(原型req.__proto__为IncomingMessage)的字段,是不是比在官网查方便多了?
    当然,我更想进一步了解这些字段是什么东西

            for (key in req) {
                    let value = req[key]
                    if (typeof value === "function") {
                            console.log(`${key} => FUNCTION`)
                            break
                    }
                    try {
                            console.log(`${key} => ${value}`)
                    } catch(e) {
                            console.log(`can't read the ${key} value`)
                    }
            }
    

    输出:

    _readableState => [object Object]
    readable => true
    can't read the _events value
    _eventsCount => 1
    _maxListeners => undefined
    socket => [object Object]
    httpVersionMajor => 1
    httpVersionMinor => 1
    httpVersion => 1.1
    complete => false
    headers => [object Object]
    rawHeaders => Host,a,User-Agent,Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0,Accept,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,Accept-Language,zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2,Accept-Encoding,gzip, deflate,Connection,keep-alive,Upgrade-Insecure-Requests,1,Cache-Control,max-age=0
    trailers => [object Object]
    rawTrailers =>
    aborted => false
    upgrade => false
    url => /
    method => GET
    statusCode => null
    statusMessage => null
    client => [object Object]
    _consuming => false
    _dumped => false
    setTimeout => FUNCTION
    

    安装模块

    npm i --save express
    

    现在,依赖模块已经被安装到node_modules文件夹下,package.json中的dependencies字段也被更新了

    node.js作为脚本执行

    新建index.js

    #!/usr/bin/env node
    
    console.log("Hello, Node.js")
    
    

    现在执行./index.js,系统就能自动调用node环境来解释运行index.js了

    Node.js就是这么的强大又简单,Be enjoy IT !

    模块、内置对象和函数

    每个.js文件都可以看作一个小模块,它们都是一个render函数的实现,这个函数原型是

    function (exports, require, module, __filename, __dirname) {; /* module body */; });
    

    其中exports是module.exports的引用。要导出函数和对象,直接重写module.exports对象即可。
    不过除了这些参数,我们还可以使用全局对象global,比如对象global.process.env可以访问环境变量。

    • require()函数
      require()函数可以加载模块和json文件
      什么叫加载模块?事实上,require()函数返回的就是render()函数的回调参数module的exports字段。
      要从当前目录加载模块和json文件,路径必须以./开头,文件后缀.js或.json可以省略。
    const log = require("./log")
    const config = require("./config.json")
    

    END

  • 相关阅读:
    bzoj3514 Codechef MARCH14 GERALD07加强版
    差分数列(学习笔记)
    mysql 数据库 replace、regexp的用法
    30岁前男人需要完成的事
    硬盘故障修复十大攻略
    网络工程师考试必备知识
    系统不能正常关机
    忘记XP登入密码的9种解决办法
    Mysql全文搜索match...against的用法
    双绞线网线的连接方式
  • 原文地址:https://www.cnblogs.com/develon/p/12013334.html
Copyright © 2011-2022 走看看