一、Node.js是什么

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine.

1. 特性

Node.js 可以解析JS代码(没有浏览器安全级别的限制),提供很多系统级别的API,如:
· 文件的读写(File System)
· 进程的管理(Process)
· 网络通信(HTTP/HTTPS)
· ......

2. 举例

2.1 浏览器安全级别的限制

Ajax测试

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>
        browser-safe-sandbox
    </div>
    <script>
        const xhr = new XMLHttpRequest();
        xhr.open('get', 'https://m.maoyan.com/ajax/moreClassicList?sortId=1&showType=3&limit=10&offset=30&optimus_uuid=A5518FF0AFEC11EAAB158D7AB0D05BBBD74C9789D9F649898982E6542C7DD479&optimus_risk_level=71&optimus_code=10',false);
        xhr.send();
    </script>
</body>

</html>

浏览器预览

browser-sync start --server --files **/* --directory

2.2 文件的读写(File System)

const fs = require('fs);
fs.readFile('./ajax.png','utf-8',(err,content)=>{
  console.log(content);
})

2.3 进程的管理(Process)

function main(arg) {
  console.log(arg);
}

main(process.argv.slice(2));

2.4 网络通信(HTTP/HTTPS)

const http = require('http');
http.createServer((req,res)=>{
  res.writeHead(200,{
    'contnt-type': 'text/plain'
  });
  res.write('hello node.js');
  res.end();
}).listen(3000);

null
4 声望0 粉丝