I would like to be able to read data received by the ascii command sent.
Below is the code that sends command to my lock controller
var express = require('express');
var router = express.Router();
var SerialPort = require('serialport');
/* GET home page */
router.get('/', function(request, response){
SerialPort.list(function (err, ports) {
ports.forEach(function(port) {
console.log(port.comName);
console.log(port.pnpId);
console.log(port.manufacturer);
});
});
var port = new SerialPort("COM5", {
baudRate: 38400
});
port.on('open', function() {
// NodeJS v4 and earlier
port.write(new Buffer('status1', 'ascii'), function(err) {
if (err) {
return console.log('Error on write: ', err.message);
}
console.log('message written');
});
});
// open errors will be emitted as an error event
port.on('error', function(err) {
console.log('Error: ', err.message);
});
});
// Important
module.exports = router;
In the doc, it mentions the use of parsers to try and read data, https://github.com/EmergingTechnologyAdvisors/node-serialport#serialportparsers--object but I am not sure how to implement it, and I would want to execute after the command status1 has been written.
Essentially logs the response of the command succesfully written to the console
There are some peculiarities.
You can open port on application start and reconnect on port close or open port on each request. It defines how work with data flow. If you send request to port then answer can contain data of previous requests (more than one). You can ignore this problem (if answer is short and request interval is enough large) or send request with assign id and search answer with this id.
SerialPort.list(function (err, ports) {
ports.forEach(function(port) {
console.log(port.comName, port.pnpId, port.manufacturer); // or console.log(port)
});
});
router.get('/', function(req, res){
function sendData(code, msg) {
res.statusCode = 500;
res.write(msg);
console.log(msg);
}
var port = new SerialPort("COM5", {
baudRate: 38400
});
port.on('open', function() {
port.write(Buffer.from('status1', 'ascii'), function(err) {
if (err)
return sendData(500, err.message);
console.log('message written');
});
});
var buffer = '';
port.on('data', function(chunk) {
buffer += chunk;
var answers = buffer.split(/\r?\n/); \\ Split data by new line character or smth-else
buffer = answers.pop(); \\ Store unfinished data
if (answer.length > 0)
sendData(200, answer[0]);
});
port.on('error', function(err) {
sendData(500, err.message);
});
});
module.exports = router;
Related
So i've been working on this for a bit:
/*
API 1 Docs: https://docs.genius.com/#/getting-started-h1
API 2 Docs: https://pastebin.com/doc_api
*/
let https = require('https')
//const qs = require('querystring');
function handler(req, res){
if(req.method == "GET"){
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.end("<html><body><form action='/' method='post'><input type='text' name='hello'><input type='submit'></form></body></html>");
} else if(req.method == 'POST'){
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.end(`<html>Success Posting!</html>`)
/*
var body;
req.on('data', function(data) {
body += data;
if (body.length > 1e6) {
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
req.connection.destroy();
}
});
req.on('end', function() {
var POST = qs.parse(body);
let data = POST.submit
res.end(`<html>${data}</html>`)
});
*/
} else {
res.writeHead(200);
res.end();
};
};
https.createServer(handler).listen(3000, function(err) {
if (err) {
console.log('Error starting https server');
} else {
console.log('Server listening on port 3000');
};
});
(Please ignore commented code)
I had it working before and all of a sudden, it stopped working, it created a form and upon submitting it it would change the page to "Success Posting" but now all of a sudden its not and ive been making small changes not knowing my problem
It appears that I need to create an http server using the http module instead of making an https server with the https module
Before:
const https = require('https')
https.createServer(handler).listen(3000, function(err) {
if (err) {
console.log('Error starting https server');
} else {
console.log('Server listening on port 3000');
};
});
After:
const http = require('http')
http.createServer(handler).listen(3000, function(err) {
if (err) {
console.log('Error starting http server');
} else {
console.log('Server listening on port 3000');
};
});
I have a route I that in order to get all the data needs to access the API server multiple times (according to the data that was given).
Now I need to add a third access to the server and it's getting rather unreadable.
The following code is working, but I have a feeling I'm not doing it right (promises?) - couldn't figure out what exactly is recommended in this case
The code: (stripped down to emphasise the point)
router.get('/', function(req, main_response) {
http.get(FIRST_API_COMMAND, function (res) {
var moment_respose_content = '';
res.on("data", function (chunk) {
moment_respose_content += chunk;
});
res.on('end',function(){
if (res.statusCode < 200 || res.statusCode > 299) {
main_response.send('error in getting moment');
return;
}
var response = JSON.parse(moment_respose_content );
if (response.success)
{
var data = response.data;
//doing something with the data
http.get(SECOND_API_COMMAND, function (res) {
res.on("data", function (chunk) {
comment_respose_content += chunk;
});
res.on('end',function(){
var response = JSON.parse(comment_respose_content);
if (response.success)
{
var comments = response.data;
main_response.render('the page', {data: data});
return;
}
});
}).on('error', function (e) {
console.log("Got error: " + e.message);
main_response.send('Error in getting comments');
});
return;
}
});
}).on('error', function (e) {
console.log("Got error: " + e.message);
main_response.send('Error in getting moment');
});
});
You can write a middleware for each remote action, and then use those middlewares before the get handler, so the get handler can simply access their results. (Promises can help if you need to start subsequent requests before waiting for earlier ones to finish, but that situation is rare.)
For example, using express middleware to fetch each remote data independently:
var request = require('request');
var express = require('express');
var app = express();
var router = express.Router();
/* middleware to fetch moment. will only run for requests that `router` handles. */
router.use(function(req, res, next){
var api_url = 'https://google.com/';
request.get(api_url, function(err, response, body) {
if (err) {
return next(err);
}
req.moment_response = response.headers["date"];
next();
});
});
/* middleware to fetch comment after moment has been fetched */
router.use(function(req, res, next){
var api_url = 'https://www.random.org/integers/?num=1&min=1&max=100&col=1&base=10&format=plain&rnd=new';
request.get(api_url, function(err, response, body){
if (err) {
return next(err);
}
req.comment_response = parseInt(body);
next();
});
});
/* main get handler: expects data to already be loaded */
router.get('/', function(req, res){
res.json({
moment: req.moment_response,
comment: req.comment_response
});
});
/* error handler: will run if any middleware called next() with an argument */
router.use(function(error, req, res, next){
res.status(500);
res.send("Error: " + error.toString());
});
app.use('/endpoint', router);
app.listen(8000);
Often the remote data you want to fetch is based on some parameter of the main request. In this case you would want to use req.param() instead of App.use() to define the data-loading middleware.
I am building my first node.js server to perform a mysql query and return results from the database. Everything works but now I cannot find the right way to pass a value from the url (query section) to the function that performs the query (the PollingLoop function). No problems to retrieve the url and to get the parameter in the handler function but to move it to pollingLoop I have tried almost all I know about javascript (not enough I see). This is my code now that fails to run because of the reference error in pollingLoop for hwkey that is not defined.
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
url = require('url'),
fs = require('fs'),
mysql = require('mysql'),
connectionsArray = [],
connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'flipper',
database: 'oclock',
port: 3306
}),
POLLING_INTERVAL = 3000,
pollingTimer;
// If there is an error connecting to the database
connection.connect(function(err) {
// connected! (unless `err` is set)
if (err) {
console.log(err);
}
});
// creating the server ( localhost:8000 )
app.listen(8000);
function handler(req, res) {
console.log("INCOMING REQUEST: "+req.method+" "+req.url);
req.parsed_url = url.parse(req.url, true);
var getp = req.parsed_url.query;
var hwkey = getp.hk;
console.log(hwkey);
fs.readFile(__dirname + '/client.html', function(err, data) {
if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading client.html');
}
res.writeHead(200);
res.end(data);
});
}
function pollingLoop(){
// Doing the database query
var query = connection.query('SELECT max(id), testo, created_by FROM flashmsgs WHERE hwk="'+hwkey+'"'),
//var query = connection.query('SELECT max(id), testo, created_by FROM flashmsgs'),
flashmsgs = []; // this array will contain the result of our db query
// setting the query listeners
query
.on('error', function(err) {
// Handle error, and 'end' event will be emitted after this as well
console.log(err);
updateSockets(err);
})
.on('result', function(flashmsg) {
// it fills our array looping on each user row inside the db
flashmsgs.push(flashmsg);
})
.on('end', function() {
// loop on itself only if there are sockets still connected
if (connectionsArray.length) {
pollingTimer = setTimeout(pollingLoop, POLLING_INTERVAL);
updateSockets({
flashmsgs: flashmsgs
});
} else {
console.log('The server timer was stopped because there are no more socket connections on the app')
}
});
};
// creating a new websocket to keep the content updated without any AJAX request
io.sockets.on('connection', function(socket) {
console.log('Number of connections:' + connectionsArray.length);
// starting the loop only if at least there is one user connected
if (!connectionsArray.length) {
pollingLoop();
}
socket.on('disconnect', function() {
var socketIndex = connectionsArray.indexOf(socket);
console.log('socketID = %s got disconnected', socketIndex);
if (~socketIndex) {
connectionsArray.splice(socketIndex, 1);
}
});
console.log('A new socket is connected!');
connectionsArray.push(socket);
});
var updateSockets = function(data) {
// adding the time of the last update
data.time = new Date();
console.log('Pushing new data to the clients connected ( connections amount = %s ) - %s', connectionsArray.length , data.time);
// sending new data to all the sockets connected
connectionsArray.forEach(function(tmpSocket) {
tmpSocket.volatile.emit('notification', data);
});
};
console.log('Please use your browser to navigate to http://localhost:8000');
just bring on hwkey variable out from handler
var hwkey;
function handler(req, res) { hwkey = ... }
pollingLoop(){console.log(hwkey);}
I am trying to display an image on a basic web page on a localhost w/ port 5000
here is main.js
var http = require('http');
var domain = require('domain');
var root = require('./root');
var image = require('./image');
function replyError(res) {
try {
res.writeHead(500);
res.end('Server error.');
} catch (err) {
console.error('Error sending response with code 500.');
}
};
function replyNotFound(res) {
res.writeHead(404);
res.end('not found');
}
function handleRequest(req, res) {
console.log('Handling request for ' + req.url);
if (req.url === '/') {
root.handle(req, res);
} else if (req.url === '/image.png'){
image.handle(req, res);
} else {
replyNotFound(res);
}
}
var server = http.createServer();
server.on('request', function(req, res) {
var d = domain.create();
d.on('error', function(err) {
console.error(req.url, err.message);
replyError(res);
});
d.run(function() { handleRequest(req, res); });
});
function CallbackToInit(){
server.listen(5000);
};
root.init(CallbackToInit);
Using callbacks I want the server to start listening(5000) only after the init function of the following code runs
var http = require('http');
var body;
exports.handle = function(req, res) {
res.writeHead(200, {
'Content-Type': 'image/png'
});
res.end(body);
};
exports.init = function(cb) {
require('fs').readFile('image.png', function(err, data) {
if (err) throw err;
body = data;
cb();
});
}
It's an assignment I can't use express
I am trying to get image.png to be displayed, I think body = data doesn't work because it can't hold an image like a string? I don't want to put any HTML into my js file.
Don't roll your own app server. Use one of the great web app frameworks like express or connect.
var express = require('express');
var app = express();
app.use(express.logger());
app.use(express.static(__dirname + '/public'));
app.listen(process.env.PORT || 5000);
Trust me, this is better.
Take a look at the node.js example for a simple http server or a tutorial/example, such as this, for serving static files through a simple server.
I have tried to pass a variable from my index.html to the database(maildata.js) through app.js(server) and get the corresponding data
I am able to get the data from the database but couldnt send that back to the server(app.js)
app.js
var express = require('express');
var maildata= require('./maildata');
var app = express();
app.configure(function(){
app.use(express.bodyParser());
});
app.get('/', function(request, response){
response.sendfile(__dirname + '/mailbox.html');
});
app.post('/mailboxpost',function(request, response) {
var input=request.query.search;
var result=maildata.getMailData(input);
response.send(result);
response.end();
});
app.listen(8888);
console.log('Server is running on port 8888');
maildata.js
exports.getMailData=function(data,response) {
var stop_name= data;
connection.query("select stop_name,stop_comment from stoplist where stop_name= '"+stop_name+"' limit 1",function(err, rows) {
if (err) {
console.log('error in fetching ' + err);
}
else{
var jsonString1= JSON.stringify(rows);
connection.query("select mailbox_sequence_no from stoplist where stop_name= '"+stop_name+"'",function(err, rows) {
if (err) {
console.log('error in fetching ' + err);
}
else{
var jsonString2 = JSON.stringify(rows);
connection.query("select party_head from stoplist where stop_name= '"+stop_name+"'", function(err, rows) {
if (err) {
console.log('error in fetching ' + err);
}
else{
var jsonString3 = JSON.stringify(rows);
var result=jsonString1+'/'+jsonString2+'/'+jsonString3;
response.send(result);
}
});
}
});
}
});
}
Thanks in Advance
How about sending response along when you call the function?
var result=maildata.getMailData(input); // something missing here
Your getMailData function expects two arguments:
exports.getMailData=function(data,response) { ... }
but you give it only one:
var result=maildata.getMailData(input);
Which makes the value of the response argument undefined.
Here is what you should do:
app.post('/mailboxpost',function(request, response) {
var input=request.query.search;
maildata.getMailData(input, response);
});
and let maildata.getMailData handle the response sending, as you did in response.send(result);
I have used asynchronous callback method in my app.js.
I got the result
var result=maildata.getMailData(input,response,function(data){
response.send(data);
response.end();
});
Thanks all