Categories
JavaScript Answers

How to clear console on Node.js on windows?

To clear console on Node.js on windows, we call the proces.stdout.write method.

For instance, we write

process.stdout.write('\033c');

to call write with '\033c' to clear the console.

Categories
JavaScript Answers

How to include external .js file in Node.js app?

To include external .js file in Node.js app, we create a module.

For instance, we write

const make = (Schema, mongoose) => {
  CarSchema = new Schema({
    brand: String,
    type: String,
  });
  mongoose.model("Car", CarSchema);
};

module.exports.make = make;

in car.js to export the make function.

Then we use it by writing

const app = require("express").createServer();
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;

require("./models/car.js").make(Schema, mongoose);

We call require to require the car.js file and call make from the returned object.

Categories
JavaScript Answers

How to fix Babel unexpected token import when running mocha tests with JavaScript?

To fix Babel unexpected token import when running mocha tests with JavaScript, we add the @babel/preset-env library.

To install it, we run

npm install @babel/preset-env --save-dev

Then in the .babelrc file, we add

{
  "presets": ["@babel/preset-env"]
}

to add the Babel preset to clear the syntax error.

Categories
JavaScript Answers

How to fix Node js Error: Protocol “https:” not supported. Expected “http:”?

To fix Node js Error: Protocol "https:" not supported. Expected "http:", we use https.get method.

For instance, we write

const http = require("http");
const https = require("https");
const url = new URL("https://www.example.com");
const client = url.protocol == "https:" ? https : client;
const req = client.get(url, (res) => {
  console.log(res);
});

to get the client according to the url‘s protocol.

We use the https client if it’s https and http if it’s http.

Then we call get with the client for the right protocol to make the get request.

Categories
JavaScript Answers

How to run npm http-server with SSL?

To run npm http-server with SSL, we create a certificate and use that to run the server.

To do this, we run

brew install mkcert
brew install nss

to install mkcert

Then we go to our project directory and run

mkcert 0.0.0.0 localhost 127.0.0.1 ::1

to create a certificate.

Then we run the server with our certificate with

http-server -S -C cert.pem -o