Node Backend Notes
Side Notes: Node Process
Note: Side notes are not necessary but are for reading in free time.
The process.exit()
method instructs Node.js to terminate the process synchronously with an exit status of code
. If code
is omitted, exit uses either the 'success' code 0
or the value of process.exitCode
if it has been set. Node.js will not terminate until all the 'exit' event listeners are called.
To exit with a 'failure' code:
import { exit } from 'node:process';
exit(1);
The shell that executed Node.js should see the exit code as 1
.
Calling process.exit()
will force the process to exit as quickly as possible, even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations to process.stdout
and process.stderr
.
In most situations, it is not actually necessary to call process.exit()
explicitly. The Node.js process will exit on its own if there is no additional work pending in the event loop. The process.exitCode
property can be set to tell the process which exit code to use when the process exits gracefully.
For instance, the following example illustrates a misuse of the process.exit()
method that could lead to data printed to stdout being truncated and lost:
import { exit } from 'node:process';
// This is an example of what *not* to do:
if (someConditionNotMet()) {
printUsageToStdout();
exit(1);
}
The reason this is problematic is that writes to process.stdout
in Node.js are sometimes asynchronous and may occur over multiple ticks of the Node.js event loop. Calling process.exit()
, however, forces the process to exit before those additional writes to stdout can be performed.
Rather than calling process.exit()
directly, the code should set the process.exitCode
and allow the process to exit naturally by avoiding scheduling any additional work for the event loop:
import process from 'node:process';
// How to properly set the exit code while letting
// the process exit gracefully.
if (someConditionNotMet()) {
printUsageToStdout();
process.exitCode = 1;
}
If it is necessary to terminate the Node.js process due to an error condition, throwing an uncaught error and allowing the process to terminate accordingly is safer than calling process.exit()
.
In Worker threads, this function stops the current thread rather than the current process.
Since — v0.1.13
Param code
— The exit code. For string type, only integer strings (e.g., '1') are allowed.
There is a small problem with environment variables while using module JS because they do not support module JS. That's why we have to make some changes in the manifest file. Here is the code for that small change:
In the package.json
, this is an experimental feature:
"scripts": {
"dev": "nodemon -r dotenv/config --experimental-json-modules src/index.js"
}
import dotenv from 'dotenv';
dotenv.config({
path: './env'
});
Prettier is a dev dependency used to format the code. Here are the settings of the .prettierrc
:
{
"singleQuote": false,
"bracketSpacing": false,
"tabWidth": 4,
"semi": true,
"trailingComma": "es5"
}
Express documentation: read it and refer
File Structure of Backend Application of Express:
One approach to connect DB in Node using Mongoose:
import mongoose from "mongoose";
import { DB_NAME } from "./constants";
import express from "express";
const app = express();
(async () => {
try {
mongoose.connect(`${process.env.MONGODB_URI}/${DB_NAME}`);
app.on("error", (error) => {
console.log("ERROR ", error);
throw error;
});
app.listen(process.env.PORT, () => {
console.log(`app is listening on port ${process.env.PORT}`);
});
} catch (error) {
console.log(error);
throw error;
}
})();
Another recommended approach to connect DB:
In this approach, we create a separate “db” folder in which we have created an index file and wrote a DB connection code, and that function has been exported. The good part of this is we can use this function anywhere in the codebase; that’s why it is the professional approach to connecting DB.
db/index.js
import mongoose from "mongoose";
import { DB_NAME } from '../constants.js';
const connectDB = async () => {
try {
const connectionInstance = await mongoose.connect(`${process.env.MONGODB_URI}/${DB_NAME}`);
// In the response, we get the connection instance object where various methods are available, like below
// This is a log I have printed connection host
console.log(`\n Mongodb has been connected !! DB HOST : ${connectionInstance.connection.host}`);
} catch (error) {
console.log('MONGODB CONNECTION FAILED: ', error);
process.exit(1);
}
};
export default connectDB;
Subscribe to my newsletter
Read articles from pranav madhukar sirsufale directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
pranav madhukar sirsufale
pranav madhukar sirsufale
🚀 Tech Enthusiast | Computer Science Graduate | Passionate about web development, app development, and data science. Skilled in Java, Node.js, React, HTML, MySQL, and Python. Always learning and sharing insights on tech, programming tutorials, and practical guides.