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.
Locate a Parent Folder with fs
We can use the 2 dots to go to the parent folder.
For instance, we can write:
fs.readFile(path.join(__dirname, '/../../foo.txt'));
We have /../
to go up one level.
2 would go up 2 levels.
The forward slash is also required.
How ‘use strict’ is Interpreted in Node.js Apps
Node interpret 'use strict'
the same way as other JavaScript apps.
It enables checks for undeclared variables, disallows setting constant values like undefined
and so on.
Illegal operations that are silent without strict mode converted to errors.
ES6 modules have strict mode enabled by default, so we don’t have to enable it explicitly.
HTTP GET Request in Express
To make a GET request in a Node app, we can use the requestify
HTTP client to make the request.
For instance, we can write:
var requestify = require('requestify');
requestify.get('http://example.com/')
.then((response) => {
response.getBody();
}
);
We can put that anywhere in our Express app to make our request.
For example, we can put in in our route handler or middleware to make the request when a request is made from the client.
Difference Between Synchronous and Asynchronous Programming
Synchronous programs are run line by line.
Async programs compute the results in an indeterminate amount of time.
We can get the results in callbacks or assign then with await
if the async code is a promise.
For instance, we can write:
database.query("SELECT * FROM table", (result) => {
console.log(result);
});
is asynchronous. It doesn’t block the main thread when this code is run.
The callback is called when the results are ready.
Synchronous code is run by writing:
const result = database.query("SELECT * FROM table");
console.log(result);
The query
method returns the result and we can get it after it’s assigned.
Some tasks like file system operations run in a different process.
Send a Message to a Specific Client with socket.io
We can use the clients
property and send
method to send a message to the specific client.
For instance, we can write:
const io = io.listen(server);
io.clients[clientId].send();
We get the client by its ID and then call send
on it.
Send a 404 Response with Express
To send a 404 response with Express, we can call res.status
to send the status code.
If we want to add a message, we can call send
after it.
For instance, we can write:
res.status(404).send('not found');
Also, we can use the sendtatus
method:
res.sendStatus(404);
Create Folder or Use Existing One if Exists
To make us create a folder or use one if it exists, we can use the mkdirp
package.
To install it, we run:
npm install mkdirp
Then we can write:
cpnst mkdirp = require('mkdirp');
mkdirp('/foo', (err) => {
//...
});
err
has the error if it’s encountered.
'/foo'
is the directory path.
The callback is called after the directory is created or that it already exists.
Since Node 10, we can also do the same thing without a library.
For instance, we can write:
fs.mkdirSync('/foo', { recursive: true })
to use or create a folder synchronously with the recursive
option.
Also, we can write:
await fs.promises.mkdir('/foo', { recursive: true })
to do the same thing asynchronously.
'/foo'
is the path.
How to Use NODE_ENV in Express
We can set the NODE_ENV
environment variable with the export
command.
For instance, we can write:
export NODE_ENV=production
Then in our Express app, we can write:
app.get('env')
to get the environment name.
Update a Specific Node Package
To update a specific Node package, we can use the npm update
command.
For instance, we can run:
npm update express
Or we can run:
npm install express@4.17.1
to update Express to the specific version.
We can also update to the latest version by running:
npm install express@latest
Conclusion
We can update packages with npm update
.
We can use async code to run long-running operations.
Also, we can send messages to a specific client.
There are HTTP clients made for Node apps.