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.
Getting Line Number in try-catch
We can get the line number with try-catch by using the stack
property.
For instance, we can write:
try {
//...
} catch(err) {
console.log(err.stack);
}
Display PDF in the Browser Using Express
To display a PDF in the browser, we set a few headers to make sure that our Express route returns a PDF.
For instance, we can write:
app.post('/url/to/hit', (req, res, next) => {
const stream = fs.readStream('/location/of/pdf');
const filename = "doc.pdf";
filename = encodeURIComponent(filename);
res.setHeader('Content-Disposition', `inline; filename=${filename}`);
res.setHeader('Content-Type', 'application/pdf');
stream.pipe(res);
});
We set the Content-Disposition
header to set the header to the PDF file’s file name.
inline
means display the data in the browser within a web page or part of a page.
Also, we’ve to set the Content-type
header to application/pdf
to make sure that the client knows that we’re responding with a PDF.
Accept POST Body from Request Using Express
To make sure that we can send POST requests to an Express sewer, we should use the body-parser
middleware.
For instance, we write:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
Then we have the routes below these 2 lines.
Now we can parse JSON payloads on the server-side.
Then on the client-side, we should have the Content-Type
request header set to application/json
.
Mixing JavaScript and TypeScript in Node.js
There are a few ways to let us mix JavaScript and TypeScript in Node apps.
We can set the --allowJs
compiler option.
We also need to set the --outDir
option to set the folder for storing the compiled files.
--checkJs
lets us check the types of JavaScript files.
Node.js Clusters with a Simple Express App
We can use an Express app in a cluster.
For example, we can write:
const cluster = require('cluster');
const express = require('express');
const app = express.createServer();
if (cluster.isMaster) {
for (let i = 0; i < 2; i++) {
cluster.fork();
}
} else {
app.configure(() => {
app.set('view options', {
layout: false
});
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(express.bodyParser());
});
app.get('/', (req, res) => {
res.render('index');
});
app.listen(8080);
}
We use the cluster
module create our cluster by calling cluer.fork
if the process is a master process.
Other, we create an instance of the Express app.
Sequelize Update with Association
We can use Sequelize to update a database entry and its association.
For instance, we can write:
const filter = {
where: {
id
},
include: [{
model: Profile
}]
};
Product.findOne(filter).then((product) => {
if (product) {
return product.Profile.updateAttributes(updateProfile).then((result) => {
return result;
});
} else {
throw new Error("product not found");
}
});
We get the Product
with a filter object.
Then we get its child association with product.Profile
to get the Profile
model.
And we call the updateAttributes
method on it.
In the filter
object, we’ve to ad the include
property with the child model we want to include.
Exclude Route from Express Middleware
To exclude a route from running an Express middleware, we can pass in the regex of the pattern of the route that we want to run.
For instance, we write:
app.use(//((?!foo).)*/, routerHandler);
We exclude the route with path /foo
with our pattern.
Then routerHandler
runs on everything except when the path is /foo
.
Render Raw HTML
We can render raw HTML by writing:
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/layout.html');
});
We use res.sendFile
to render the HTML located in the absolute path.
Get File Type of File
To get the type of the file, we can use the mime
module.
For instance, we can write:
const mime = require('mime');
const type = mime.getType('/path/to/file.txt');
We just call the getType
method.
There’s also the mime-types
method:
const mime = require('mime-types');
const type = mime.lookup(fileImageTmp);
Conclusion
We can use the body-parser
to parse the request body.
Also, we can use a package to parse the mime type of a file.
Sequelize can update associations.
The cluster
module can update child associations.
We can respond with PDFs with a cluster.