Categories
JavaScript Answers

How to separate routes on Node.js and Express 4?

Sometimes, we want to separate routes on Node.js and Express 4.

In this article, we’ll look at how to separate routes on Node.js and Express 4.

How to separate routes on Node.js and Express 4?

To separate routes on Node.js and Express 4, we can put our routes into a separate and call require to add them.

For instance, we write

app.js

const express = require('express');
const app = express();

app.use(require('./routes'));

const server = app.listen(8000, () => {
  const host = server.address().address
  const port = server.address().port
  console.log("listening at http://%s:%s", host, port)
})

to call app.use with require('./routes') to add the routes in routes.js.

Then in routes.js, we write

const express = require('express');
const router = express.Router();

router.use((req, res, next) => {
  next();
});

router.get('/', (req, res) => {
  res.send('home page');
});

router.get('/about', (req, res) => {
  res.send('About us');
});


module.exports = router;

to create a router object with express.Router.

Then we call router.use and router.get to add the middleware and add GET endpoints.

Next, we set module.exports to router to export router so we can use require('./routes') to include the router and call app.use to add the routes.

Conclusion

To separate routes on Node.js and Express 4, we can put our routes into a separate and call require to add them.

Categories
JavaScript Answers

How to run multiple statements in one query with node-mysql?

Sometimes, we want to run multiple statements in one query with node-mysql.

In this article, we’ll look at how to run multiple statements in one query with node-mysql.

How to run multiple statements in one query with node-mysql?

To run multiple statements in one query with node-mysql, we can call connection.query with all our SQL statements.

For instance, we write

connection.query('SELECT ?; SELECT ?', [1, 2], (err, results) => {
  if (err) {
    throw err;
  }

  const [r1, r2] = results
  console.log(r1);
  console.log(r2);
});

to call query with 2 SELECT statements separated by a semicolon.

And then we pass in an array the values for the ? in the SQL code.

Next, we pass in a callback that has the SELECT query results stored in the results parameter.

As a result, r1 is [{1: 1}] and r2 is [{2: 2}].

Conclusion

To run multiple statements in one query with node-mysql, we can call connection.query with all our SQL statements.

Categories
JavaScript Answers

How to set navigation timeout with Node.js Puppeteer?

Sometimes, we want to set navigation timeout with Node.js Puppeteer.

In this article, we’ll look at how to set navigation timeout with Node.js Puppeteer.

How to set navigation timeout with Node.js Puppeteer?

To set navigation timeout with Node.js Puppeteer, we can call goto with the timeout option.

For instance, we write

await page.goto(url, {
  waitUntil: 'load',
  timeout: 0
});

to call goto with the url to navigate to the URL.

And we call it with an object that has timeout set to 0 to set the navigation timeout to 0ms.

Conclusion

To set navigation timeout with Node.js Puppeteer, we can call goto with the timeout option.

Categories
JavaScript Answers

How to scroll down until you can’t anymore with Puppeteer?

Sometimes, we want to scroll down until you can’t anymore with Puppeteer.

In this article, we’ll look at how to scroll down until you can’t anymore with Puppeteer.

How to scroll down until you can’t anymore with Puppeteer?

To scroll down until you can’t anymore with Puppeteer, we can scroll periodically down the page until the height scrolled is bigger than or equal to the scroll height of the scroll container.

For instance, we write

const puppeteer = require('puppeteer');

const autoScroll = async (page) => {
  await page.evaluate(async () => {
    await new Promise((resolve, reject) => {
      let totalHeight = 0;
      const distance = 100;
      const timer = setInterval(() => {
        const scrollHeight = document.body.scrollHeight;
        window.scrollBy(0, distance);
        totalHeight += distance;

        if (totalHeight >= scrollHeight) {
          clearInterval(timer);
          resolve();
        }
      }, 100);
    });
  });
}

const openPageAndScroll = async () => {
  const browser = await puppeteer.launch({
    headless: false
  });
  const page = await browser.newPage();
  await page.goto('https://www.yoursite.com');
  await page.setViewport({
    width: 1200,
    height: 800
  });
  await autoScroll(page);
  //...
  await browser.close();
}

openPageAndScroll()

to define the autoScroll function.

In it, we call setInterval with a callback that calls window.scrollBy to scroll by distance pixels down.

We then add distance to totalHeight.

And then if totalHeight >= scrollHeight, we call clearInterval to clear the timer and call resolve to resolve the promise.

And we scroll every 100ms.

Next, we define the openPageAndScroll function that calls autoScroll and use await to wait for the promise to resolve before running the next line.

Conclusion

To scroll down until you can’t anymore with Puppeteer, we can scroll periodically down the page until the height scrolled is bigger than or equal to the scroll height of the scroll container.

Categories
JavaScript Answers

How to implement login authentication in Node.js?

Sometimes, we want to implement login authentication in Node.js.

In this article, we’ll look at how to implement login authentication in Node.js.

How to implement login authentication in Node.js?

To implement login authentication in Node.js, we can add our own middleware to check the session object before calling the route handler.

For instance, we write

const checkAuth = (req, res, next) => {
  if (!req.session.userId) {
    res.send('You are not authorized');
  } else {
    next();
  }
}

app.get('/my_secret_page', checkAuth, (req, res) => {
  res.send('You are logged in');
});

app.post('/login', (req, res) => {
  const post = req.body;
  if (post.user === 'john' && post.password === 'johnspassword') {
    req.session.userId = johnsUserId;
    res.redirect('/my_secret_page');
  } else {
    res.send('Bad user/pass');
  }
})

app.get('/logout', (req, res) => {
  delete req.session.userId;
  res.redirect('/login');
});

to define the checkAuth middleware function that checks if req.session.userId is present.

We set req.session.userId in the /login route when login is successful.

If req.session.userId isn’t set, we call res.send with a 'You are not authorized'.

Otherwise, we call next to call the route middleware.

Next, we add the endpoints with app.get and app.post.

We add checkAuth as an argument in /my_secret_page to run checkAuth to check for presence of userId before running the route.

In the /login route handler, we check the user and password from the req.body request body object.

And if they both match, we call res.redirect to redirect to /my_secret_page since login is successful.

In /logout, we delete req.session.userId to remove the current user info and call res.redirect to redirect to /login.

Conclusion

To implement login authentication in Node.js, we can add our own middleware to check the session object before calling the route handler.