To fix "Error: Cannot find module ‘ejs’ " with Node.js, we install the ejs library.
To install it, we run
npm install ejs
in our project folder to install the ejs package with npm.
Web developer specializing in React, Vue, and front end development.
To fix "Error: Cannot find module ‘ejs’ " with Node.js, we install the ejs library.
To install it, we run
npm install ejs
in our project folder to install the ejs package with npm.
To define an array as an environment variable in Node.js, we can define it as a JSON array.
For instance, we write
ANY_LIST = ["A", "B", "C"]
to add the ANY_LIST environment variable to our .env file.
Then we write
const LIST = JSON.parse(process.env.ANY_LIST);
to get the ANY_LIST environment variable with process.env.ANY_LIST.
And we parse it into an array with JSON.parse.
To create document if not exists, otherwise, update and return document in either case with Node.js Mongoose, we call the findOneAndUpdate method.
For instance, we write
const query = {};
const update = { expire: new Date() };
const options = { upsert: true, new: true, setDefaultsOnInsert: true };
Model.findOneAndUpdate(query, update, options, (error, result) => {
if (error) return;
//...
});
to call findOneAndUpdate with the query and the update object that has the values to update in the documents.
And then the updated document are set as the value of the result parameter.
To fix the ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client error with Node.js, we make sure we only return a response once.
For instance, we write
if (!user) {
errors.email = "User not found";
res.status(404).json({ errors });
return;
}
to call res.status and json to return the 404 status and the { errors } as the response body to send the response.
Then we use return to stop running the function to make sure another response isn’t sent.
To run Mocha tests with extra options or parameters with JavaScript, we get the values from process.argv.
For instance, we write
const argv = require("minimist")(process.argv.slice(2));
console.log("config", argv.config);
to get the command args with process.argv in the Mocha test file.
We then parse it with the minimist library into an object and get the config config.
Then we run the test with
mocha test.js --config=VALUE