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.

Categories
JavaScript Answers

How to pipe the same readable stream into multiple (writable) targets with Node.js?

To pipe the same readable stream into multiple (writable) targets with Node.js, we call the pipe method on each stream.

For instance, we write

const spawn = require("child_process").spawn;
const PassThrough = require("stream").PassThrough;

const a = spawn("echo", ["hi user"]);
const b = new PassThrough();
const c = new PassThrough();

a.stdout.pipe(b);
a.stdout.pipe(c);

let count = 0;
b.on("data", (chunk) => {
  count += chunk.length;
});
b.on("end", () => {
  console.log(count);
  c.pipe(process.stdout);
});

to create 2 PassThrough objects.

Then we call pipe to pipe our input from a to to the PassThrough objects with pipe to write to them.

We get the data written from the 'data' event handler’s chunk parameter.