Categories
JavaScript Answers

How to parse Query String in Node.js?

To parse Query String in Node.js, we use the querystring module.

For instance, we write

const http = require("http");
const queryString = require("querystring");

http
  .createServer((oRequest, oResponse) => {
    let oQueryParams;
    if (oRequest.url.indexOf("?") >= 0) {
      oQueryParams = queryString.parse(oRequest.url.replace(/^.*\?/, ""));
      console.log(oQueryParams);
    }

    oResponse.writeHead(200, { "Content-Type": "text/plain" });
    oResponse.end("Hello world.");
  })
  .listen(3000, "127.0.0.1");

to call queryString.parse to parse the request URL that we got from oRequest.url.

We get pack an object with the keys and values of the query string.

Categories
JavaScript Answers

How to go back 1 folder level with __dirname with Node.js?

To go back 1 folder level with __dirname with Node.js, we use the path.join method.

For instance, we write

const path = require("path");
const configFile = path.join(__dirname, "../test/karma.conf.js");

to call path.join with __dirname and a string with the path one level above __dirname with ../ to return a path one level above __dirname.

Categories
JavaScript Answers

How to pass execution arguments to app using Node.js PM2?

To pass execution arguments to app using Node.js PM2, we use the --

For instance, we run

pm2 start app.js -- --prod --second-arg --third-arg

to start app.js with start.

And then we pass in the arguments after --.

Categories
JavaScript Answers

How to convert Mongoose docs to JSON with Node.js?

To convert Mongoose docs to JSON with Node.js, we use the lean method.

For instance, we write

UserModel.find()
  .lean()
  .exec((err, users) => {
    return res.end(JSON.stringify(users));
  });

to call lean to convert the results returned from find to a plain object.

Then we get the results from the users parameter in the exec callback.

users is a plain JavaScript array.

Categories
JavaScript Answers

How to extend TypeScript Global object in node.js?

To extend TypeScript Global object in node.js, we add a type declaration file.

For instance, we write

declare module NodeJS {
  interface Global {
    spotConfig: any;
  }
}

to add a type declaration in vendor.d.ts to add the Global interface into the project type definition with the properties we want to add to the global interface.

Therefore, we can use the spotConfig global variable without type errors.