I'm using Node.js, Express.js, and node-serial port. Call to get the list of serial ports is asynchronous and I'm trying to make it synchronous with Fibrous, but can't get it to work. Here's the code:
var express = require('express');
var serialPort = require("serialport");
var fibrous = require('fibrous');
var app = express();
...
app.post('/', function(req, res, next) {
console.log('before execution');
detectDevices.sync();
console.log('after execution')
});
...
var detectDevices = fibrous(function() {
var ports = serialPort.sync.list();
console.log('mfg='+ports[0].manufacturer);
});
Error says "Can't wait without a fiber". I've tried to use 'Futures' from Fibrous and some other example, but can't make it work in the POST handler of Express.js. What is the proper way to have my detectDevices execute synchronously in the app.post() function?
Mike S is correct. The following code works very well:
var express = require('express');
var serialPort = require("serialport");
var fibrous = require('fibrous');
var app = express();
app.use(fibrous.middleware);
...
app.post('/', function(req, res, next) {
console.log('before execution');
detectDevices.sync();
console.log('after execution')
});
...
var detectDevices = fibrous(function() {
var ports = serialPort.sync.list();
for (var i = 0; i < ports.length; i++) {
console.log(port.comName);
console.log(port.pnpId);
console.log(port.manufacturer);
}
});
Related
In the code below, what is best way to pass information from app.js to choices.js ?
Currently, I put them all in a variable called answer.
Is that the best way to do it ?
Thank you.
These are the code in app.js:
var express = require("express");
var cors = require("cors");
var bodyParser = require("body-parser");
var app = express();
var sql = require('msnodesqlv8');
:
var choicesTerm = [];
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(function (req, res, next) {
console.log(`${req.method} request for '${req.url}' -
${JSON.stringify(req.body)}`);
next();
});
var connStr = "Driver={SQL Server Native Client 11.0};....";
sql.open(connStr, function (err, conn) {
var pm = conn.procedureMgr();
pm.callproc('mySP',sessionID, function (err, results) {
:
pm.callproc('mySp2', function (err, results) {
:
if (results.length)
{
var row = results[0];
var Answers = [];
Answers = row.Answers.split("|");
for (var i = 0, len = Answers.length; i < len; i++) {
var answer = {value: Answers[i], description: Answers[i], question: row.text, detail: row.detail}; //--> pass information to choices.js
choicesTerm[i] = answer;
}
}
})
});
});
app.use(express.static("./public"));
app.use(cors());
app.get("/choices-api", function(req, res) {
res.json(choicesTerm);
});
These are the code in choices.js:
$(document).ready(function () {
$.getJSON('/choices-api', printTerms);
});
function printTerms(terms) {
var question = terms[0].question; //--> This is passed from app.js
var detail = terms[0].detail; //--> This is passed from app.js
}
The problem I'm having is, the content that I try to send in my post request to the server doesn't get sent, but the request works.
Here's the code for the client:
$("#searchBtn").click(function(e){
try{
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/search/searchRequest", true);
console.log(($("#searchedSymptoms").val())) // gets posted in the console correctly
xhttp.setRequestHeader("Content-type", "text/plain"); // doesn't work without it either
xhttp.send($("#searchedSymptoms").val());
//xhttp.send(JSON.stringify($("#searchedSymptoms").val())); // doesn't work either
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
console.log(xhttp.responseText); // gets the correct response from server
}
else{
console.log(xhttp.responseText);
}
};
}
catch(err){
console.log(err);
}
});
And here's the server-side code:
var express = require("express");
var router = express.Router();
router.post("/searchRequest", function(req, res, next){
console.log("must get the client request:");
console.log(req.body);
//console.log(JSON.stringify(req.body)); // doesn't work either
});
In the server, what get's outputed to the console is this:
{}
Any thoughts on what I'm doing wrong ?
You need to use a text body-parser, Express won't do it by default, here's an example, using pretty much the same server side code you are:
"use strict";
var express = require("express");
var router = express.Router();
var bodyParser = require("body-parser");
router.post("/searchRequest", function(req, res, next){
console.log("must get the client request:");
console.log("SearchRequest: " + req.body);
res.end('ok', 200);
});
var port = 8081;
var app = express();
app.use(bodyParser.text());
app.use(router);
app.listen(port);
console.log("Express listening on port " + port);
You can configure the way the text body parser operates exactly by using the guide here:
https://www.npmjs.com/package/body-parser#bodyparsertextoptions
I have the following node express function:
var express = require('express');
var app = express();
// Listen on port 8000, IP defaults to 127.0.0.1
var server = app.listen(8000, function() {
console.log("node express app started at http://localhost:8000");
});
app.get("/test",
function(error, request, response, next) {
request.set("Content-Type", "text/html; charset=UTF-8");
if (error) {
request.status(403);
return next();
}
var id = request.query.snuid;
var currency = request.query.currency;
var mac_address = request.query.mac_address;
var display_multiplier = request.query.display_multiplier;
//
request.status(200);
});
When I load up the browser and enter in the url:
http://localhost:8000/test?snuid=1234¤cy=1000&mac_address=00-16-41-34-2C-A6&display_multiplier=1.0
Im not sure why I am getting this error!? Not sure, it should work based on the documentation and examples I have seen. Any help would be appreciated.
I think is because you want to use a middleware and not a route, so maybe your code can be write in this way:
var express = require('express');
var app = express();
app.use(function(err, request, response, next) {
if (error) {
request.status(403);
return next();
}
});
app.get("/test", function(request, response, next) {
response.set("Content-Type", "text/html; charset=UTF-8");
var id = request.query.snuid;
var currency = request.query.currency;
var mac_address = request.query.mac_address;
var display_multiplier = request.query.display_multiplier;
//
response.status(200).end();
});
// Listen on port 8000, IP defaults to 127.0.0.1
var server = app.listen(8000, function() {
console.log("node express app started at http://localhost:8000");
});`
I wrote a gateway for my microservices system.
Gateway was written in node.js
This gateway forwards the request to inside microservices, and responds client after getting result of their processing.
But memory consumed by this gateway continually increased, 24Mb increased every hour.
Could you help me to clarify why:
The following is code:
var express = require('express');
var requestify = require('requestify');
var app = express();
var request = require('request');
var config = require('./config.js');
var API_ERROR = 'error';
var DISCOVERY_NOTHING = 'nothing' ;
var TIMEOUT = 10000 ;//ms
function registerEntry(path,entryId) {
app.use(path, function(req, res) {
requestify.get(config.discovery+"?service_id="+entryId, {timeout:TIMEOUT}).then( function(response) {
var apiUrl = response.getBody() ;
if(apiUrl==DISCOVERY_NOTHING) {
res.send(API_ERROR);
}
var url = apiUrl + req.url ;
console.log(url);
req.pipe(request(url)).pipe(res).on('error', function(e) {
res.send(API_ERROR);
});
});
});
}
registerEntry('/authen','altp.authen') ;
registerEntry('/profile','altp.profile');
registerEntry('/question','altp.question');
registerEntry('/gameplay','altp.gameplay');
registerEntry('/admin','altp.admin');
app.listen(80, function() {
console.log('listening at 80');
});
I have an express route in a Node application that uses Mongoose for querying a Mongo database. There is a promise used in the get request to find items and I am not sure how to test this promise.
I am not very familiar with unit testing node applications.
Here is the code for the express route, this works but I am not sure how to test it:
var express = require('express');
var router = express.Router();
var promise = require('bluebird');
// bluebird.promisifyAll is used on Mongoose in app.js
var ItemModel = require('./itemModel');
router.get('/', function(req, res, next) {
ItemModel.findAsync()
.then(function(items) {
res.status(200).send(items);
})
.catch(function(err) {
next(err);
});
});
module.exports = router;
Here is what I have stubbed out in the test so far. I am not sure how to test the promise in the routes.get method :
describe('ItemRoute', function() {
var express = require('express');
var bodyParser = require('bodyParser');
var supertest = require('supertest');
var sinon = require('sinon');
var expect = require('chai').expect;
var assert = require('chai').assert;
var ItemModel = require('./ItemModel');
var ItemRoute = require('ItemRoute');
var uri = '/items/';
var agent;
beforeEach(function(done) {
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(uri, releaseNotesRoute);
agent = supertest.agent(app);
done();
});
describe('GET', function() {
it('returns an empty array when no items are stored in Mongo', function() {
// Not sure how to test the route here with a get that
// uses a promise, ItemModel.findAsync().then
});
});
});
to able to use promises in test, you should have to install sinon-as-promises module from npm. Then you can mock ItemModel like this:
var itemModelMock = sinon.mock(ItemModel);
itemModelMock.expects('findAsync').resolves([]);