Like any kind of apps, there are difficult issues to solve when we write Node apps.
In this article, we’ll look at some solutions to common problems when writing Node apps.
Correctly Exporting async Functions in Node.js
We can export an async function like any other function.
For instance, we can write:
async function doSomething() {
// ...
}
module.exports.doSomething = doSomething;
We export doSomething
like we can with any other function.
ReadFile in Base64 Nodejs
We can read a file into a base64 string by using the readFileSync
method.
For instance, we can write:
const fs = require('fs');
const str = fs.readFileSync('/path/to/file.jpg', { encoding: 'base64' });
We pass in the 2nd argument with an object.
It has the encoding
property set to 'base64'
so that we can parse the file into a base64 string.
It’s returned and assigned to str
.
Find and Update Subdocument with Mongoose
We can find and update a subdocument with the findOneAndUpdate
method.
For instance, we can write:
Person.findOneAndUpdate(
{ "_id": personId, "address._id": address._id },
{
"$set": {
"address.$": address
}
},
(err, doc) => {
console.log(doc);
}
);
We call the findOneAndUpdate
method with a few arguments.
The first is the query to find the object to update.
We query both the parent document and the subdocument with it.
We query the person
document by ID, and address
with the address._id
.
The 2nd argument is the $set
method to set the value for the address.$
to set the address subdocument.
The $
is the positional operator variable.
It’s used to get the subdocument that matches the given position.
Then the callback has the results once the operation is done.
Skip Subsequent Mocha Tests from Spec if One Fails
Mocha has a bail
operation to skip the remaining tests if one fails.
We can also use b
for short.
Returning data from Axios API
To get data from an HTTP request made by Axios, we can return the response.data
object in our then
callback.
For instance, we can write:
axios.get(url)
.then(response => {
return response.data;
})
then(data => {
res.json(data);
})
We call res.json
with the response data after the request is made successfully.
Read the Body of a Fetch Promise
We can get the body of a Fetch promise by using the json
method to convert the response object to a JSON object.
For instance, we can write:
fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => console.log(data))
We called response.json()
to get the JSON.
Parse XLSX with Node and Create JSON
To make parsing XLSX files easy in a Node app, we can use the xlsx
package.
We can use it by writing:
const XLSX = require('xlsx');
const workbook = XLSX.readFile('spreadsheet.xlsx');
const [sheetName] = workbook.SheetNames;
const json = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName])
We use the xlsx
package.
Then we can use the readFile
to read the spreadsheet with the given path.
The workbook.SheetNames
property get the sheet names from the XLSX file.
We get the first name with our example.
Then we call sheet_to_json
to convert the sheet with the given name.
We get the sheet by using the workbook.Sheets
object.
Check if a JSON is Empty in NodeJS
We can check if a JSON object is empty with the Object.keys
method.
For example, we can write:
Object.keys(obj).length === 0;
where obj
is the JSON object we want to check.
Send Flash Messages in Express
A flash message is a message that’s stored during a session.
We can use the connect-flash
middleware to send a flash message to the template.
To install the package, we run:
npm install connect-flash
Then we can write:
const flash = require('connect-flash');
const app = express();
app.configure(function() {
app.use(express.cookieParser(''));
app.use(express.session({ cookie: { maxAge: 60000 }}));
app.use(flash());
});
app.get('/flash', (req, res) => {
req.flash('info', 'flash message');
res.redirect('/');
});
app.get('/', (req, res) => {
res.render('index', { messages: req.flash('info') });
});
We set the flash message with req.flash
.
The first argument is the key of the message.
The 2nd argument is the message itself.
We can get the message by the key if we use req.flash
with one argument as we did on the '/'
route.
Conclusion
We can export async functions like any other function.
The connect-flash
package lets us store messages that are available during the session.
The xlsx
package lets us parse data from XLSX files.
Subdocuments can be updated with Mongoose.
We can get the response data with various HTTP clients.