Categories
JavaScript Answers

How to create a basic static file server in Node.js?

To create a basic static file server in Node.js, we use Express.

For instance, we write

const express = require("express");
const app = express();
const port = process.env.PORT || 4000;

app.use(express.static(__dirname + "/public"));
app.listen(port);

to create a file server by calling express.static to expose the /public folder as a static folder.

We call app.listen to start a web server.

Categories
JavaScript Answers

How to use an include with attributes with Node Sequelize?

To use an include with attributes with Node Sequelize, we set the attribute property.

For instance, we write

Payment.findAll({
  where: {
    DairyId: req.query.dairyid,
  },
  attributes: {
    exclude: ["createdAt", "updatedAt"],
  },
  include: {
    model: Customer,
    attributes: ["customerName", "phoneNumber"],
  },
});

to call findAll to add the attributes property to exclude.

And we add include with the columns of Customer to include.

Categories
JavaScript Answers

How to configure Axios to use SSL certificate with JavaScript?

To configure Axios to use SSL certificate with JavaScript, we call axios.get with a https agent object.

For instance, we write

const httpsAgent = new https.Agent({
  rejectUnauthorized: false,
  cert: fs.readFileSync("./usercert.pem"),
  key: fs.readFileSync("./key.pem"),
  passphrase: "YYY",
});

axios.get(url, { httpsAgent });

to create an https.Agent object with the cert certificate, key key file, and the passphrase.

Then we call axios.get with an object with the httpsAgent to use it to make secure requests.

We can also write

const httpsAgent = new https.Agent({
  rejectUnauthorized: false,
  cert: fs.readFileSync("./usercert.pem"),
  key: fs.readFileSync("./key.pem"),
  passphrase: "YYY",
});

const instance = axios.create({ httpsAgent });

to create a new Axios instance with axios.create.

Categories
JavaScript Answers

How to fix ‘Error: Couldn’t find preset “es2015” relative to directory “/Users/username”‘ with JavaScript?

To fix ‘Error: Couldn’t find preset "es2015" relative to directory "/Users/username"’ with JavaScript, we install the Babel preset package.

To install it, we run

npm install babel-cli babel-preset-es2015

to install the Babel packages to clear the error.

Categories
JavaScript Answers

How to create an empty file in Node.js?

To create an empty file in Node.js, we use the open method.

For instance, we write

const fs = require("fs");
fs.open(path, "wx", (err, fd) => {
  // handle error
  fs.close(fd, (err) => {
    // handle error
  });
});

to call open with the path to open the file at the path.

We create the file since we called it with the w permission.

And then we call close to close the file.