I have this code in the file bmiCalculator.ts
import { isNotNumber } from "./utils";
export default function calculateBmi(height: number, weight: number) {
const bmi = weight / Math.pow(height / 100, 2);
if (bmi < 18.5) {
return "Underweight";
} else if (bmi >= 18.5 && bmi < 25) {
return "Normal (healthy weight)";
} else {
return "Overweight";
}
}
const parseArguments = (args: string[]) => {
if (args.length < 4) throw new Error("Not Enough Arguments");
if (args.length > 4) throw new Error("Too many arguments");
if (!isNotNumber(args[2]) && !isNotNumber(args[3])) {
return {
height: Number(args[2]),
weight: Number(args[3]),
};
} else {
throw new Error("Arguments are not of the correct type");
}
};
const { height, weight } = parseArguments(process.argv);
console.log(calculateBmi(height, weight));
And also this code in the file index.ts
import express from "express";
import calculateBmi from "./bmiCalculator";
const app = express();
app.get("/hello", (_req, res) => {
res.send("Hello Full Stack!");
});
app.get("/bmi", (req, res) => {
const height = Number(req.query.height);
const weight = Number(req.query.weight);
const bmi = calculateBmi(height, weight);
res.send({ weight, height, bmi });
});
const PORT = 3002;
app.listen(PORT, () => console.log(`server running on port ${PORT}`));
I am having this error while running the express server.
Error: Not Enough Arguments
But why?? I am not running the parseArgument function. I am only importing the calculateBmi function. So why this error?
Right now, I can only run the code by commenting out the non-exported code in bmiCalculator.ts
>Solution :
Yes, as soon as you import a module (here the module is just a file), it is executed.
If the module contains only exported objects, then there is no side effect.
If the module contains some root level expressions (like const { height, weight } = parseArguments(process.argv);
in your case), they are executed. In particular, you should see your next console.log
printing.