Categories
JavaScript Answers

How to log Node Express JavaScript to a output file?

To log Node Express JavaScript to a output file, we use the express.logger method.

For instance, we write

const logFile = fs.createWriteStream("./myLogFile.log", { flags: "a" });

app.use(express.logger({ stream: logFile }));

to create the logFile write stream with createWriteStream.

We call createWriteStream with the log file path and an object with flag set to 'a' for append.

Then we call express.logger to with an object with stream set to logFile to return a middleware that we use in our app to add logging to the file.

Categories
JavaScript Answers

How to create or update with Node Sequelize?

To create or update with Node Sequelize, we use the upsert method.

For instance, we write

User.upsert({ a: "a", b: "b", username: "john" });

to call upsert with an object with the value to create or update.

It’ll look for the item to update by the primary key.

Categories
JavaScript Answers

How to press Enter button in JavaScript Puppeteer?

To press Enter button in JavaScript Puppeteer, we call the page.keyword.press method.

For instance, we write

await page.keyboard.press("Enter");

to call page.keyboard.press to press the enter key on the page.

Categories
JavaScript Answers

How to loop through an array without using array size with Node?

To loop through an array without using array size with Node, we use the forEach method.

For instance, we write

const myArray = ["1", "2", 3, 4];

myArray.forEach((value) => {
  console.log(value);
});

to call forEach with a callback that gets the entry in myArray being looped through.

We get the value being looped through from value.

Categories
JavaScript Answers

How to fix await is not working for Node request module?

To fix await is not working for Node request module, we switch to the node-fetch module.

To use it, we write

const url = "http://www.example.com";
try {
  const response = await fetch(url);
  const json = await response.json();
  return { message: json.message, status: json.type };
} catch (error) {
  console.log(error);
}

to call fetch with the url to make a get request to it.

It returns a promise so we can use await to get the response.

And then we use await again to get the response body returned by the promise returned by response.json.