Categories
JavaScript Answers

How to bind Express to a specific IP address with Node?

To bind Express to a specific IP address with Node, we call listen with the IP address to bind to.

For instance, we write

const server = app.listen(3000, "127.0.0.1", onServerListening);

to call app.listen with the IP address to bind to as the 2nd argument to bind to 127.0.0.1.

Categories
JavaScript Answers

How to fix “Cannot GET /” error with Connect on Node.js?

To fix "Cannot GET /" error with Connect on Node.js, we use the connect.static method.

For instance, we write

const connect = require("connect");

const app = connect().use(connect.static(__dirname + "/public"));
app.listen(8180);

to call connect.static to expose the /public folder as a static files folder.

And then we call use to add the returned middleware to the app.

Then we can see the files in the folder when we go to /

Categories
JavaScript Answers

How to execute bash command in Node.js and get exit code?

To execute bash command in Node.js and get exit code, we call exec.

For instance, we write

const dir = exec("ls -la", (err, stdout, stderr) => {
  console.log(stdout);
});

dir.on("exit", (code) => {
  console.log(code);
});

to call exec to run the ls -la command.

We get the output from stdout in the callback.

Then we call dir.on to listen for the exit event.

And we get the exit code from code in the callback.

Categories
JavaScript Answers

How to ping from a Node.js app?

To ping from a Node.js app, we call exec.

For instance, we write

const sys = require("sys");
const exec = require("child_process").exec;

exec("ping -c 3 localhost", (error, stdout, stderr) => {
  sys.puts(stdout);
});

to call exec to run the ping command.

And then we get the output from stdout in the callback.

Categories
JavaScript Answers

How to make synchronous database queries with Node.js?

To make synchronous database queries with Node.js, we use the synchronize module.

For instance, we write

const express = require("express");
const bodyParser = require("body-parser");
const mysql = require("mysql");
const sync = require("synchronize");

const db = mysql.createConnection({
  host: "localhost",
  user: "user",
  password: "password",
  database: "database",
});

db.connect((err) => {
  if (err) {
    console.error("error connecting: " + err.stack);
    return;
  }

  const save = async () => {
    const post = { id: newId };
    const query = sync.await(
      db.query("INSERT INTO mainTable SET ?", post, sync.defer())
    );
    const newId = query.insertId;
    const post = { foreignKey: newId };
    db.query("INSERT INTO subTable SET ?", post, (err, result) => {
      if (err) {
        throw err;
      }
    });
  };
});

to define the save function.

In it, we call sync.await to wait for the query to finish before we move to the next line of code.

We have the save function in the connect callback so we only make queries when the connection is established.