To create and read session with Node Express, we set the req.session property.
For instance, we write
req.session.email = req.param("email");
to set req.session.email to the req.param value to store the value in the session.
Web developer specializing in React, Vue, and front end development.
To create and read session with Node Express, we set the req.session property.
For instance, we write
req.session.email = req.param("email");
to set req.session.email to the req.param value to store the value in the session.
To fix Node fs.createWriteStream does not immediately create file, we call write to write the file content.
For instance, we write
const tempFile = fs.createWriteStream(tempFilepath);
tempFile.on("open", (fd) => {
http.request(url, (res) => {
res
.on("data", (chunk) => {
tempFile.write(chunk);
})
.on("end", () => {
tempFile.end();
fs.renameSync(tempFile.path, filepath);
return callback(filepath);
});
});
});
to create the tempFile write stream with createWriteStream.
And then we call res.on to listen for the data event to get the data.
We call tempFile.write with chunk to write the chunk to the write stream.
And we call tempFile.end to stop writing when the end event is emitted, which happens when all the data is received.
To check if an environment variable is set in Node.js, we use the in operator.
For instance, we write
if ("DEBUG" in process.env) {
console.log(process.env.DEBUG);
} else {
console.log("Env var IS NOT SET");
}
to check if the DEBUG property is in process.env with "DEBUG" in process.env to check if the DEBUG environment variable is set.
To use async await and .then together with JavaScript, we replace then with await.
For instance, we write
const f = async () => {
try {
const response = await fetch("http://no-such-url");
} catch (err) {
alert(err);
}
};
to call fetch to return a promise with the response.
And we use await to get the response from the promise.
To return Mongoose results from the find method, we can promisfy Mongoose.
For instance, we write
const Promise = require("bluebird");
const mongoose = require("mongoose");
Promise.promisifyAll(mongoose);
const results = await Promise.props({
users: users.find().execAsync(),
articles: articles.find().execAsync(),
});
res.render("profile/profile", results);
to call promisifyAll to promisify mongoose.
Then we call Promise.props with an object with the promises as values.
We call find with execAsync to return a promise with the query resylts.
Then we get the results array with the returned results.