Categories
JavaScript Answers

How to use Node.js require inside TypeScript file?

To use Node.js require inside TypeScript file, we call require with import or use the import statement.

For instance, we write

import sampleModule = require("module-name");

to require the module-name module with require and import.

Or we write

import * as sampleModule from "module-name";

to import the module-name module as a default import.

Categories
JavaScript Answers

How to use app.configure in with Node.js Express?

To use app.configure in with Node.js Express, we call app.use.

For instance, we write

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

app.use(/*****/);
app.use(/*****/);

app.get("/", (req, res) => {
  //...
});

to call app.use to load middlewares before we call app.get to add a get route handler.

Categories
JavaScript Answers

How to use font-awesome icons from node_modules with JavaScript?

To use font-awesome icons from node_modules with JavaScript, we install the font-awesome package.

To install it, we run

npm install font-awesome --save-dev

Then we import the installed module with

@import url('../node_modules/font-awesome/css/font-awesome.min.css');

with CSS.

Categories
JavaScript Answers

How to append to New Line in Node.js?

To append to New Line in Node.js, we use some file methods.

For instance, we write

const os = require("os");

const processInput = (text) => {
  fs.open("H://log.txt", "a", 666, (e, id) => {
    fs.write(id, text + os.EOL, null, "utf8", () => {
      fs.close(id, () => {
        console.log("file is updated");
      });
    });
  });
};

to call fs.open to open the file.

Then we call fs.write to write the file with text and the os.EOL new line character.

We then close the file with fs.close after writing to it with the id.

Categories
JavaScript Answers

How to send Content-Type: application/json post with Node.js?

To send Content-Type: application/json post with Node.js, we call the request function.

For instance, we write

const request = require("request");

const options = {
  uri: "https://www.example.com/urlshortener/v1/url",
  method: "POST",
  json: {
    longUrl: "http://www.google.com/",
  },
};

request(options, (error, response, body) => {
  if (!error && response.statusCode === 200) {
    console.log(body.id);
  }
});

to call request with the options object to make a request.

The method is set to 'POST' to make a post request.

The json property is set to an object with the JSON request body data.