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.
Get Path from the Request
We can get the path from the request by using the request.url
to get parse the request URL.
For instance, we can write:
const http = require("http");
const url = require("url");
const onRequest = (request, response) => {
const pathname = url.parse(request.url).pathname;
console.log(pathname);
response.writeHead(200, { "Content-Type": "text/plain" });
response.write("hello");
response.end();
}
http.createServer(onRequest).listen(8888);
All we have to do is to get the request.url
property to get the URL.
Then we can parse it with the url
module.
We can then get the pathname
to get the relative path.
Convert Relative Path to Absolute
We can convert a relative path to an absolute path by using the path
module’s resolve
method.
For example, we can write:
const resolve = require('path').resolve
const absPath = resolve('../../foo/bar.txt');
We call resolve
with a relative path to return the absolute path of the file.
Get the String Length in Bytes
We can get the string length in bytes by using the Buffer.byteLength
method.
For instance, we can write;
const byteLength = Buffer.byteLength(string, 'utf8');
We pass in a string
to Buffer.byteLength
to get the string length in bytes.
Get Data Passed from a Form in Express
To get data passed in from a form in Express, we can use the body-parser
package to do that.
Then to get the parsed results, we can get it from the req.body
property.
We can write:
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/game', (req, res) => {
res.render('game', { ...req.body });
});
We call app.post
to create a POST route, which gets the request body via req.body
because we called bodyParser.urlencoded
to parse URL encoded payloads.
extended
set to true
lets the body-parser
accept JSON like data within the form data including nested objects.
With this option, we don’t have to send key-value pairs as we do with traditional HTML form send.
Running Multiple Express Apps on the Same Port
We can use app.use
to incorporate multiple Express apps and run them on the same port.
For instance, we can write:
app
.use('/app1', require('./app1').app)
.use('/app2', require('./app2').app)
.listen(8080);
We require app1
and app2
to use the routes from both of them in one app.
Then we call listen
to listen to requests in port 8080.
Change Working Directory with NodeJs child_process
We can change the working directory with the cwd
option.
For example, we can write:
const exec = require('child_process').exec;
exec('pwd', {
cwd: '/foo/bar/baz'
}, (error, stdout, stderr) => {
// work with result
});
We call exec
with an object with the cwd
property to set the current working directory.
Then we get the result in the callback.
Upload a Binary File to S3 using AWS SDK for Node.js
We can upload a binary file to S3 using the Node.js AWS SDK by using the AWS package.
For instance, we can write:
const AWS = require('aws-sdk');
const fs = require('fs');
AWS.config.update({ accessKeyId: 'key', secretAccessKey: 'secret' });
const fileStream = fs.createReadStream('zipped.tgz');
fileStream.on('error', (err) => {
if (err) {
console.log(err);
}
});
fileStream.on('open', () => {
const s3 = new AWS.S3();
s3.putObject({
Bucket: 'bucket',
Key: 'zipped.tgz',
Body: fileStream
}, (err) => {
if (err) {
throw err;
}
});
});
We use the aws-sdk
package.
First, we authenticate with AWS.config.update
.
Then we create a read stream from the file with createReadStream
.
Then we listen to the file being opened with by attaching a listener to the 'open'
event.
We then create an AWS.S3
instance.
And we call putObject
to upload the file.
Bucket
is the bucket name.
Key
is the path to the file.
Body
is the read stream of the file we created.
We also listen to the error
event in case any errors are encountered.
Conclusion
We can get the path of the request with the request.url
property if we’re using the http
module to listen to requests.
To convert relative to absolute paths, we can use the path
module’s resolve
method.
We can upload files with S3 by creating a read stream and call putObject
.
We can set the current working directory with exec
.