windows下搭建node.js服务提供本地测试

近期构建一套本地服务测试EMQX规则引擎,需要在本地搭建web服务提供接收消息捣鼓一下

一:查看本地是否有node环境

如果不是这样的 需要去官网,下载符合自己电脑的版本

http://nodejs.cn/download/

下载好之后使用傻瓜安装大法安装成功  

node  -v   

npm   -v

二:本地找个目录创建文件夹,创建一个.js文件

    console.log('111111');
    'use strict'
    const http = require('http')
    const execSync = require('child_process').execSync
    // 初始化全局变量用于计数
    console.log('222222');
    let msg_num = 0
    http.createServer((req, res) => {
		console.log('333333');
      let body = ''
      req.on('data', (data) => {
        body = body + data
      })
      req.on('end', () => {
        body = body.toString()
		console.log(body);
        try {
          const message = JSON.parse(body)
          // 附加时间戳
          /** @type {number} */
          message.ts = Date.now()
          message.index = msg_num
		  console.log(body);
          // 持久化数据到磁盘,实际根据业务处理
          execSync(`echo '${JSON.stringify(message)}' >> message.log`)
          msg_num = msg_num + 1
          res.end(msg_num.toString())
        } catch (e) {
          res.end('-1')
        }
      })
    }).listen(8080, () => {
      console.log('Listen on 8080')
    }) // 监听 8080 端口

三:到F盘目录下 cmd

出现窗口之后  输入 node 目录 js文件全名

启动成功!

原文地址:https://www.cnblogs.com/innocenter/p/15097864.html