Strange Node await never unblocks - node.js

Node v8.3 + Express + using async / await complete source code below where await doesn't return unless I moved the terminal!!
// Express
const express = require('express');
const app = express();
// Lodash
const _ = require('lodash');
// DBR
const dbr = require('./build/Release/dbr');
dbr.initLicense("t0068MgAAAGvV3VqfqOzkuVGi7x/PFfZUQoUyJOakuduaSEoI2Pc8+kMwjrojxQgE5aJphmhagRmq/S9lppTkM4w3qCQezxk=");
// Promisify
const {promisify} = require('util');
const decodeFilePromise = promisify(dbr.decodeFileAsync);
app.get('/', async (req, res) => {
console.log("Received a barcode scan request!");
try {
const oneDimensionType = 0x3FF;
const scannedResults = await decodeFilePromise('test.jpg', oneDimensionType);
const imeiResults = _.uniq(_.map(_.filter(scannedResults, ['format', 'CODE_128']), 'value'));
console.log(`Successfully scanned the image: ${imeiResults}`);
res.send(`IMEI results: ${imeiResults}`);
}
catch (err) {
console.log(`Failed to scan the image: ${err}`);
res.send('Could not scan the barcode!');
}
});
app.listen(3000, () => {
console.log('Example app listening on port 3000!');
});
What do I mean by "unless I moved the terminal" ? Please see the attached GIF: https://youtu.be/HW_MqLzEC9M

Related

Connect mongodb v5 to nodejs

How to connect new mongodb v5 to nodejs
const express = require('express');
const app = express();
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
async function main() {
await client.connect();
}
const collection = client.db('internfeb').collection('dashboard');
const port = process.env.PORT || 7710;
app.get('/health',async(req,res) => {
const output = []
const cursor = collection.find({});
for await (const doc of cursor) {
output.push(doc)
}
cursor.closed;
res.send(output)
})
app.post('/addUser',async(req,res) => {
await collection.insertOne(req.body)
res.send('Data Added')
})
app.listen(port,() => {
main()
console.log(`Running on thr port ${port}`)
})
You should initialize collection after the client has connected:
const express = require('express');
const app = express();
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
let collection;
async function main() {
try {
await client.connect();
collection = client.db('internfeb').collection('dashboard');
} catch (err) {
console.log(err);
process.exit(1);
}
}
const port = process.env.PORT || 7710;
app.get('/health', async (req, res) => {
const output = [];
const cursor = collection.find({});
for await (const doc of cursor) {
output.push(doc);
}
cursor.closed;
res.send(output);
});
app.post('/addUser', async (req, res) => {
await collection.insertOne(req.body);
res.send('Data Added');
});
app.listen(port, () => {
main();
console.log(`Running on thr port ${port}`);
});

Chai testing TypeError: Converting circular structure to JSON

I'm a new learner express.js I want to test simple post and get operations with tdd mechanism. I created the test, route, index and db files but when I try to test POST method it gives me this error.
This is my routes/task.js
const express = require('express');
const router = express.Router();
router.post("/api/task", async (req,res) => {
try {
const task = await new Task(req.body).save();
res.send(task);
} catch (error) {
res.send(error);
}
})
This is my test/task.js
let chai = require("chai");
const chaiHttp = require("chai-http");
const { send } = require("process");
let server = require("../index");
//Assertion Style
chai.should();
chai.use(chaiHttp);
describe('Tasks API', () => {
/**
* Test the POST Route
*/
describe('POST /api/task', () => {
it("It should POST a new task", () => {
const task = {task: "Wake Up"};
chai.request(server)
.post("/api/task")
.send(task)
.end((err, response) => {
response.should.have.status(201);
response.body.should.be.a('string');
response.body.should.have.property('id');
response.body.should.have.property('task');
response.body.should.have.property('task').eq("Wake Up");
response.body.length.should.be.eq(1);
done();
});
});
});
});
This is my db.js
var sqlite3 = require('sqlite3').verbose()
const DBSOURCE = "db.sqlite"
let db = new sqlite3.Database(DBSOURCE, (err) => {
if (err) {
// Cannot open database
console.error(err.message)
throw err
}else{
console.log('Connected to the SQLite database.')
db.run(`CREATE TABLE IF NOT EXISTS todo (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task text
)`,
(err) => {
if (err) {
// Table already created
console.log(err);
}
});
}
});
module.exports = db
And this is my index.js
const connection = require('./db');
const express = require('express');
const app = express();
const cors = require("cors");
const port = process.env.PORT || 8080;
app.use(express.json());
app.use(cors());
app.get('/', (req, res) => {
res.send('Hello World');
});
app.post('/api/task', (req, res) => {
res.status(201).send(req);
});
app.listen(port, () => console.log(`Listening on port ${port}...`));
module.exports = app;
The thing that I try to do is building a test case to test the post method. I think I couldn't built the correct relations the files.
Currently, just by doing a POST request to /api/task, the error will appear. That is because of these lines in index.js:
app.post('/api/task', (req, res) => {
res.status(201).send(req);
});
The req parameter is circular, hence cannot be JSON-stringified.
Solution
In routes/task.js export the router:
const express = require('express');
const router = express.Router();
router.post("/api/task", async (req,res) => {
try {
const task = await new Task(req.body).save();
res.send(task);
} catch (error) {
res.send(error);
}
})
// By adding this line you can export the router
module.exports = router
In index.js, include the routes/task.js file and pass it to app.use(...), also remove the now-obsolete /api/task route:
const connection = require('./db');
const express = require('express');
const app = express();
const cors = require("cors");
const taskRoutes = require("./routes/task")
const port = process.env.PORT || 8080;
app.use(express.json());
app.use(cors());
app.get('/', (req, res) => {
res.send('Hello World');
});
app.use(taskRoutes)
app.listen(port, () => console.log(`Listening on port ${port}...`));
module.exports = app;
This way we got rid of the circular structure stringifying and the tests should now pass.

Async/Await with node-pg on digitalocean not returning anything

Hi I am trying to fetch data from server/index.js api endpoint data.getData() which is provided from api/data.js which in turn gets it's configuration and connection object from db/index.js. The problem is that the async/await is not returning anything and in the dev console network says pending. I don't receive any errors either. The code is below. Using node-pg with pool.query.
//server/index.js
const express = require("express");
const data = require("./api/data")
const PORT = process.env.PORT || 3001;
const app = express();
app.use(express.json())
app.get('/', async (req, res) => {
// res.status(200).send('Hello World!');
await data.getData()
.then(response => {
res.status(200).send(console.log(response));
})
.catch(error => {
res.status(500).send(error);
})
console.log("server running")
})
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
//api/data.js
const db = require('../db/index.js');
const getData = async () => {
const query = {
// text: 'SELECT COUNT(*) as count FROM "public"."Subregions-USA";',
text: 'SELECT Now()',
// values: ['B007RKDGVQ'],
// rowMode: 'array',
};
const dbResults = await db.query(query)
.then((data) => JSON.stringify(data))
.catch(error => {
console.log(error)
})
console.log("database response test")
return dbResults
}
// getData()
module.exports = {getData}
The setup is pretty simple but i can't understand why it is not working.
I am trying to connect to postgresql in digital ocean and all the connections and configs are correct. I have used the same setup similar but with electron.js and it works. I am able to retrieve the data easily.
Any help appreciated.
You should avoid using both async/await and then/catch at the same time. Use one of them.
server/index.js
const express = require("express");
const data = require("./api/data")
const PORT = process.env.PORT || 3001;
const app = express();
app.use(express.json())
app.get('/', async (req, res) => {
// res.status(200).send('Hello World!');
try {
const result = await data.getData();
res.status(200).send(result);
} catch (error) {
res.status(500).send(error);
}
console.log("server running")
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
api/data.js
const db = require('../db/index.js');
const getData = async () => {
const query = {
// text: 'SELECT COUNT(*) as count FROM "public"."Subregions-USA";',
text: 'SELECT Now()',
// values: ['B007RKDGVQ'],
// rowMode: 'array',
};
const dbResults = await db.query(query);
console.log("database response test", dbResults)
return JSON.stringify(dbResults)
}
module.exports = {getData}
Ok I have found the problem and it has nothing to do with the logic itself but more with the package I installed for PostgreSQL.
Instead of installing npm i pg I did instead npm i node-pg for some stupid reason.
After uninstalling and installing the correct package I am able to work with the PostgreSQL response.

Await for function before end()

edit: added a bit more code.
const express = require('express');
var bodyParser = require('body-parser');
const app = express();
var urlencodedParser = bodyParser.urlencoded({extended: false})
const {google} = require('googleapis');
const {PubSub} = require('#google-cloud/pubsub');
const iot = require('#google-cloud/iot');
const API_VERSION = 'v1';
const DISCOVERY_API = 'https://cloudiot.googleapis.com/$discovery/rest';
app.get('/', urlencodedParser, (req, res) => {
const projectId = req.query.proyecto;
const cloudRegion = req.query.region;
const registryId = req.query.registro;
const numSerie = req.query.numSerie;
const command = req.query.command;
const client = new iot.v1.DeviceManagerClient();
if (client === undefined) {
console.log('Did not instantiate client.');
} else {
console.log('Did instantiate client.');
sendCom();
}
async function sendCom() {
const formattedName = await client.devicePath(projectId, cloudRegion, registryId, numSerie)
const binaryData = Buffer.from(command);
const request = {
name: formattedName,
binaryData: binaryData,
};
return client.sendCommandToDevice(request).then(responses => res.status(200).send(JSON.stringify({
data: OK
}))).catch(err => res.status(404).send('Could not send command. Is the device connected?'));
}
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
module.exports = app;
I have this function, that I call after the client initiate: sendCom();
async function sendCom() {
const formattedName = await client.devicePath(projectId, cloudRegion, registryId, deviceId)
const binaryData = Buffer.from(command);
const request = { name: formattedName, binaryData: binaryData, };
client.sendCommandToDevice(request)
.then(responses => {
res.status(200).send(JSON.stringify({ data: OK })).end();
})
.catch(err => {
res.status(404).send('Could not send command. Is the device connected?').end();
});
}
My problem is that sendCommandToDevice gets executed perfectly, however I get the catch error.
As I understand it, it's because in the .then ends the connection.
I've looked at this and thats's what I tried, however I'm not sure I understand what's going on.
You can not use send with end.
end() is used when you want to end the request and want to respond with no data.
send() is used to end the request and respond with some data.
You can found more about it here.

Google Cloud IoT sendCommandToDevice node.js sends command but catches error

I have this in Google's App Engine (node.js).
My device gets all the commands but I still get the Could not send command. Is the device connected? error.
BTW, already tried this: Await for function before end()
And same result.
Trying to follow this example BTW:
https://cloud.google.com/nodejs/docs/reference/iot/0.2.x/v1.DeviceManagerClient#sendCommandToDevice
const express = require('express');
var bodyParser = require('body-parser');
const app = express();
var urlencodedParser = bodyParser.urlencoded({
extended: false
})
const iot = require('#google-cloud/iot');
app.get('/', urlencodedParser, (req, res) => {
res.setHeader('Content-Type', 'application/json');
const projectId = req.query.proyecto;
const cloudRegion = req.query.region;
const registryId = req.query.registro;
const numSerie = req.query.numSerie;
const command = req.query.command;
const client = new iot.v1.DeviceManagerClient();
if (client === undefined) {
console.log('Did not instantiate client.');
} else {
console.log('Did instantiate client.');
sendCom();
}
async function sendCom() {
const formattedName = client.devicePath(projectId, cloudRegion, registryId, numSerie)
const binaryData = Buffer.from(command);
const request = {
name: formattedName,
binaryData: binaryData,
};
return client.sendCommandToDevice(request).then(responses => res.status(200).end(JSON.stringify({
data: OK
}))).catch(err => res.status(404).end('Could not send command. Is the device connected?'));
}
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
module.exports = app;
On my end I should get status 200 and OK but it doesn't happen.

Resources