Preliminary node.js

Node.js Introduction


  • Node.js was born in 2009, Node.js uses language written in C ++, is a Javascript runtime environment. Node.js is a JavaScript runtime environment Chrome V8 engine, allowing JavaScript to run out of the browser, you can use the JavaScript language to write server-side code.

Install Node.js

Node.js official website to download the stable version, node version is stable version even-odd version of a non-stable version.

  • mac mounted directly or brew to install

  • After installation is automatically installed Node.js NPM (Node Package Manager): package management tools;
  • To see if the installation is complete, and view node version number by instruction node -v; npm -v to see npm version.

Use Node.js to achieve the first server

Initial feelings Node.js

//引入http模块
let http = require("http");
//创建一个服务器
let serve = http.createServer((req,res)=>{
    console.log("hello");
    res.end("hello world");
})
//设置端口号
serve.listen(3000);
  • Google Chrome default non-secure port list, try to avoid the following ports.

    1, // tcpmux
    7, // echo
    9, // discard
    11, // systat
    13, // daytime
    15, // netstat
    17, // qotd
    19, // chargen
    20, // ftp data
    21, // ftp access
    22, // ssh
    23, // telnet
    25, // smtp
    37, // time
    42, // name
    43, // nicname
    53, // domain
    77, // priv-rjs
    79, // finger
    87, // ttylink
    95, // supdup
    101, // hostriame
    102, // iso-tsap
    103, // gppitnp
    104, // acr-nema
    109, // pop2
    110, // pop3
    111, // sunrpc
    113, // auth
    115, // sftp
    117, // uucp-path
    119, // nntp
    123, // NTP
    135, // loc-srv /epmap
    139, // netbios
    143, // imap2
    179, // BGP
    389, // ldap
    465, // smtp+ssl
    512, // print / exec
    513, // login
    514, // shell
    515, // printer
    526, // tempo
    530, // courier
    531, // chat
    532, // netnews
    540, // uucp
    556, // remotefs
    563, // nntp+ssl
    587, // stmp?
    601, // ??
    636, // ldap+ssl
    993, // ldap+ssl
    995, // pop3+ssl
    2049, // nfs
    3659, // apple-sasl / PasswordServer
    4045, // lockd
    6000, // X11
    6665, // Alternate IRC [Apple addition]
    6666, // Alternate IRC [Apple addition]
    6667, // Standard IRC [Apple addition]
    6668, // Alternate IRC [Apple addition]

    6669, // Alternate IRC [Apple addition]

Modular

First, why would modular

  • Is to achieve a simple page interaction logic, a few words that JavaScript early stages of development, now with the expanding front-end code

    This time targeting the embedded JavaScript as scripting language shaken, JavaScript does not provide any significant help for the organization code, JavaScript code is very simple organizational norms is not sufficient to manage such a large-scale code;

Two, Node.js specification of modular commonjs

  • CommonJS JS performance is to make your specifications, because there is no js function modules so CommonJS came into being, it wants js can run anywhere, not just browsers.

    1. Create a custom module

    • The introduction of a document in the form of module

      home.js executable file

      //通过require来引入
      require("./aModule"); //注意一定要有"./",文件后缀可加可不加。

      amodule.js file

      console.log("我是amodule模块111");
    • The introduction of a folder in the form of modules

      • home.js executable file
      require("./aModuledir"); //必须加"./"

      aModuleDir in the index.js file will automatically find index.js file folder under execution

      console.log("我是aModule模块文件夹");
      • Of course, you can configure the default boot file, the new package.json within the folder to specify the executable file
      {
        "name":"aModule",
        "version":"1.0.0",
        "main":"test.js"
      }
  • Custom module export demand

    Export by module.exports; ___dirname, __filename

    module.exports = {
        a:"我是a的值",
        b(){
            console.log("我是导出的b函数");
        }
    }

    The introduction of the export file

    let mymodule = require("bModule");
    console.log(mymodule.a);
    mymodule.b();

    Or derived by exports

    exports.fn = function(){
        console.log("我是fn函数");  
    }

    Importing files

    let myfn = require("bModule").fn;
    myfn();
    // 或者 通过解构赋值 
    let { fn } = require("bModule");
    fn();
  • Module loading priority, then the first file directory;

2, built-in module;

nodejs built-in module has: Buffer, C / C ++ Addons, Child Processes, Cluster, Console, Cr

ypto,Debugger,DNS,Domain,Errors,Events,File System,

Globals, HTTP, HTTPS, Modules, Net, OS, Path, Process, P unycode, Query Strings, Readline, REPL, Stream, String De coder, Timers, TLS / SSL, TTY, UDP / Datagram, URL, Utilities, V8, VM, ZLIB; no need to install built-in module, the module needs to be installed externally;

npm package manager

Address NPM (Node Package Manager) is the official website of npm official website

  • npm common commands;
    • npm init: create a boot file package.json
    • npm help (npm -h): View npm help
    • npm version (npm -v): View npm version;
    • npm search: Find
    • npm install (npm i): installation default in the current directory, if not node_modules will create folders;
      • npm install module_name -S or --save i.e. npm install module_name --save write dependencies
      • npm install module_name -D or -save-dev i.e. npm install module_name --save-dev written devDependencies
      • npm install module_name -g global mount (using command line)
      • Specifies the version of the installation module npm i module_name @ 1.0 by the "@" symbol specified;
    • npm update(npm -up):更新
    • npm remove or npm uninstall: Delete
    • See npm root path of the current package is installed or mounted to view the global path through npm root -g;

fs module

  • fs is the file operating module, all file operations are divided synchronous and asynchronous, characterized by the synchronization will add "Sync" as: reading files asynchronously "readFile", reads the file sync "readFileSync";

    File Operations

    • File reads:

      • Asynchronous read
      let fs = require("fs");
      fs.readFile("1.txt",(err,data)=>{
          if(err){
              return console.log(err);
          }
          console.log(data.toString());
      })
      • Synchronous read the file
      let fs = require("fs");
      let res = fs.readFileSync("1.txt");
      console.log(res.toString());
    • File write:

      let fs = require("fs");
      //flag配置  "a":追加写入,"w":写入,"r":读取
      fs.writeFile("2.txt","我是要写入的内容",{flag:"w"},err=>{
          if(err){
              return console.log(err);
          }
          console.log("写入成功");   
      })
    • File deletion

      fs.unlink("2.txt",err=>{
          if(err){
              return console.log(err);
          }
          console.log("删除成功");
      })
    • Copy files

      • First read the file and then write to the file
      function mycopy(src,dest){
         fs.writeFileSync(dest,fs.readFileSync(src));
      }
      mycopy("1.txt","4.txt");
    • Modify the file name, directory can also be operated by rename

      fs.rename("1.txt","5.txt",function (err) {
          if(err){
              console.log(err);
          }else{
              console.log("修改成功");
          }
      });
    • Determine whether a file exists

      fs.exists("4.txt",function (exists) {
          console.log(exists);
      })

buffer buffer

  • the creation of buffer
    • Created directly
    • Array creation
    • Create a string
    • Garbage processing
    • buffer conversion tostring

stream flow

  • stream stream: the stream data processing inseparable
    • Principle stream
    • Obtaining stream data
      • pipe
      • data
      • end
    • implemented method of copy stream
    • Implemented method of loading a flow view

to sum up

  • Installation and use of nodejs

  • Server and client

  • Modular commonjs

  • Use fs module (file operations and directory operations)

  • stream
  • buffer

Guess you like

Origin www.cnblogs.com/forcee/p/12301077.html