获取扫描仪中的信息并传到指定服务器 app.js代码
1const http = require('http'); 2const SerialPort = require("serialport"); 3const port = new SerialPort('com3'); 4const fs = require('fs'); 5var querystring = require('querystring'); 6const config=JSON.parse(fs.readFileSync('profile.json').toString()).config; 7 8 9port.on('open',function(){ 10 port.write('main screen turn on ',function(err){ 11 if(err){ 12 return console.log('打开串口失败: ' ,err.message); 13 } 14 console.log('打开串口成功'); 15 }); 16}) 17 18port.on('data',function(data){ 19 console.log('Data: '+data); 20 var data = {'code': data};//这是需要提交的数据 21 var content = querystring.stringify(data); 22 23 var options = config.address 24 options.path = config.address.path +'?'+ content 25 var req = http.request(options, function (res) { 26 // console.log('STATUS: ' + res.statusCode); 27 // console.log('HEADERS: ' + JSON.stringify(res.headers)); 28 res.setEncoding('utf8'); 29 res.on('data', function (chunk) { 30 console.log('BODY: ' + chunk); 31 }); 32 }); 33 34 req.on('error', function (e) { 35 console.log('发起请求失败: ' + e.message); 36 }); 37 38 req.end(); 39}); 40 41port.on('error',function(err){ 42 console.log('打开串口失败: ',err.message); 43}) 44 45 46 47
package.json
1{ 2 "name": "HidPos", 3 "version": "1.0.0", 4 "main": "app.js", 5 "dependencies": { 6 "cors": "^2.8.5", 7 "express": "^4.16.4", 8 "serialport": "^9.0.7", 9 "ws": "^7.4.4" 10 } 11} 12
profile.json 配置文件的信息
1{ 2 "config": { 3 "scanningGun": "", 4 "address":{ 5 "hostname": "192.168.0.16", 6 "port": 8091, 7 "path": "/login", 8 "method": "GET" 9 } 10 } 11} 12
