Blogger Information
Blog 94
fans 0
comment 0
visits 92761
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
【Node】node常用模块(示范)
可乐随笔
Original
1605 people have browsed it

node常用模块(示范)

1.1 Node中的模块

  1. // Node中的模块
  2. // CommonJS
  3. // 模块 -> JS文件
  4. // 所有成员私有,只有导出才能用
  5. /**
  6. * 1. 核心模块: 无须声明直接用
  7. * 2. 自定义: 文件
  8. * 3. 第三方模块: npm包
  9. */
  10. // 1. 核心模块
  11. const fs = require('fs');
  12. // console.log(fs);
  13. const http = require('http');
  14. // console.log(http);
  15. // 2. 文件模块: 用户自定义,先声明,再导入
  16. let site = require('./m1.js');
  17. console.log(site);
  18. console.log(site.getSite());
  19. console.log('-----------------');
  20. site = require('./m2.js');
  21. console.log(site);
  22. console.log(site.getSite());

1.2 node http服务器

  1. // * http
  2. const http = require('http');
  3. http
  4. .createServer(function (request, response) {
  5. // text
  6. // response.writeHead(200, { 'Content-Type': 'text/plain' });
  7. // response.end('Hello PHP.CN');
  8. // html
  9. // response.writeHead(200, { 'Content-Type': 'text/html' });
  10. // response.end('<h1 style="color:red">PHP.CN</h1>');
  11. // json
  12. response.writeHead(200, { 'Content-Type': 'application/json;charset=utf-8' });
  13. response.end(`
  14. {
  15. "id": 3456,
  16. "name": "笔记本电脑",
  17. "price": 10000
  18. }
  19. `);
  20. })
  21. .listen(8081, () => {
  22. console.log('Server running at http://127.0.0.1:8081/');
  23. });

1.3 文件模块和路径模块

  1. // 文件模块
  2. var fs = require('fs');
  3. fs.readFile(__dirname + '/file.txt', (err, data) => {
  4. if (err) return console.error(err);
  5. console.log(data.toString());
  6. });
  7. // path 模块
  8. const str = './node/hello.js';
  9. const path = require('path');
  10. // 绝对路径
  11. console.log(path.resolve(str) + '\n');
  12. // 目录
  13. console.log(path.dirname(str) + '\n');
  14. // 文件名
  15. console.log(path.basename(str) + '\n');
  16. // 扩展名
  17. console.log(path.extname(str) + '\n');
  18. const obj = {
  19. root: '',
  20. dir: './demo',
  21. base: 'test.js',
  22. ext: '.js',
  23. name: 'test',
  24. };
  25. console.log(path.format(obj));
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post