nodejs学习笔记01-helloworld

1,593 阅读1分钟

1.安装nodejs

http://nodejs.cn/官网安装nodejs稳定版,推荐使用nvm安装标语版本控制,过程可以参考另外一篇文章

image.png

2.检查nodejs是否安装成功

终端输入:node -v

image.png 打印出版本号即为安装成功。

第一个服务 hello world

const http = require('http'); // 引入http模块

// 创建服务 
http.createServer((req, res)=>{
  // 设置响应头
  res.writeHead(200, {'Content-type': "text/html;charset='utf-8'"});
  
  // 给页面输出内容 <meta charset="UTF-8"> 给html设置编码格式,否则中文会乱码;
  res.write('<head><meta charset="UTF-8"><head>')
  res.write('<div>你好 nodejs</div>')
  res.end('你好 nodejs');
  
}).listen(8086) // 监听的端口

使用node helloworld.js启动服务,打开浏览器输入网址:http://localhost:8086/,服务已经启动了。

image.png