Categories
JavaScript Answers

How to properly add 1 month from now to current date in moment.js and JavaScript?

To properly add 1 month from now to current date in moment.js and JavaScript, we call the add method.

For instance, we write

const d = moment().add(1, "months").calendar();

to call moment to create a moment object with the current date and time.

Then we call add to add 1 month to the date.

And we call calendar to return the date string with the date.

Categories
JavaScript Answers

How to check if a variable exists with Node Jade Template Engine?

To check if a variable exists with Node Jade Template Engine, we use an if statement.

For instance, we write

if locals.username
  p= username
else
  p No Username!

to check is the locals.username variable exists with if locals.username.

Categories
JavaScript Answers

How to send a success status to browser from Node.js and Express?

To send a success status to browser from Node.js and Express, we call the sendStatus method.

For instance, we write

res.sendStatus(200)

to call the sendStatus method to send a 200 response code.

Categories
JavaScript Answers

How to run Node.js app with ES6 features enabled?

To run Node.js app with ES6 features enabled, we set the presets option.

For instance, in package.json, we write

{
  "dependencies": {
    "babel-cli": "^6.0.0",
    "babel-preset-es2015": "^6.0.0"
  },
  "scripts": {
    "start": "babel-node --presets es2015 app.js"
  }
}

to add the babel-preset-es2015 package.

And we set the --presets option when we run babel-node to enable the ES6 features.

Categories
JavaScript Answers

How to read and write a text file in TypeScript and Node.js?

To read and write a text file in TypeScript and Node.js, we call the readFileSync function.

For instance, we write

import { readFileSync } from "fs";

const file = readFileSync("./filename.txt", "utf-8");

to call readFileSync to read filename.txt into a Unicode string.