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.
Synchronous Requests in Node.js
We can make synchronous requests in Node apps with the sync-request
package.
For instance, we can write:
const request = require('sync-request');
try {
const res1 = request('GET', '/yrl1');
const res2 = request('GET', '/url2');
//...
}
catch (e) {
//...
}
We import the sync-request
package an use its request
function to make requests synchronously.
However, as usual, synchronous code is blocking, so it shouldn’t be used in production apps.
However, it may be good for scripts.
Get Schema of a MongoDB Database Which Defined in Another Model with Mongoose
We can get the Mongoose schema with the model
method.
For instance, we can write:
const PersonSchema = require('mongoose').model('person').schema
to get the Mongoose schema for the person
collection.
Detect Node.js or Browser Environments
To check in a piece of code whether it’s running in Node or the browser, we can check if the window
object exists.
If it does, then we know it’s running in the browser.
Otherwise, it’s running in Node.
For instance, we can write:
const app = window ? window : global;
to get the global variable of the corresponding platforms.
window
is the global object for the browser.
global
is the global object for Node.
Difference Between readFile and readFileSync
fs.readFile
takes a callback and reads the file asynchronously.
The callback is called with the result whenever it’s done.
readFileSync
reads the file synchronously and returns the content of it when it’s done.
We should use readFile
in most apps since it doesn’t block other parts of an app from running.
However, readFileSync
are good for scripts where we aren’t running anything else other than the code in the script sequentially.
How to Detect the Environment in an Express.js App
We can use the app.get
method to get the environment variable in an Express app.
For instance, we can write:
app.get('env')
to get the environment variable.
Then we can write:
if (app.get('env') === 'development') {
//...
}
to check if the app is running in the 'development'
environment.
Parsing Form Data Request Payloads in Express
The body-parser
package lets us parse request payloads in Express.
For instance, we can write:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/post',(req, res) => {
console.log(req.body)
})
We require the body-parser
so that we can call the json
method to make it parse JSON.
And we call urlencoded
so that it can parse form data payloads.
extended
means that we can parse JSON that’s nested in form-data requests.
Then the parsed request payload will be available in req.body
.
Alternatively, we can use the express-formidable
middleware to do the same thing.
We can install it by running:
npm install express-formidable
Then we can use it by writing:
const express = require('express');
const formidable = require('express-formidable');
const app = express();
app.use(formidable());
app.post('/upload', (req, res) => {
res.send(JSON.stringify(req.fields));
});
We just pass in the formidable
middleware.
Then we get the parsed request payload with the req.fields
object.
Run Async Mocha Shared Test Code in Order
We can run async Mocha tests in order by using the before
hook to run code that’s shared between multiple tests.
For instance, we can write:
let someCondition = false;
//...
describe('is dependent on someCondition', () => {
const beforeTest = (done) => {
if (someCondition) {
done();
}
else {
setTimeout(() => beforeTest(done), 1000);
}
}
before((done) => {
beforeTest(done);
});
it('does something', () => {
// ...
});
})
We check that someCondition
is met before we run our tests with the beforeTest
function.
Otherwise, we call beforeTest
again after 1 second.
We do that until someCondition
is true
.
We pass in done
to the beforeTest
function so that we can call it when someConditional
finally becomes true
.
Once done
is called, the test will be run.
Conclusion
We can run some checks before a test is run and wait for a condition to become true before running it.
We can use the sync-request
package to run synchronous requests.
However, it’s blocking the rest of the app so it should probably only be used in scripts.
We can detect the platform that a piece of code is run in by checking which global object is available.