登录  /  注册
博主信息
博文 94
粉丝 0
评论 0
访问量 111209
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
【Node】node常用模块(示范)
可乐随笔
原创
1805人浏览过

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));
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学