DEV Community

Cover image for How to check if a node file is running as a script?
Sibelius Seraphini for Woovi

Posted on

How to check if a node file is running as a script?

What is a Script?

A script is a code that you can run directly from your terminal.

It is a runnable code

Here is a minimal node script

const run = async () => {
};

(async () => {
  try {
    await run();
  } catch (err) {
    // eslint-disable-next-line
    console.log(err);
    process.exit(1);
  }

  process.exit(0);
})();
Enter fullscreen mode Exit fullscreen mode

How we run scripts at Woovi monorepo?

We run node scripts in many ways:

node path/to/myScript.ts

yarn es path/to/myScript.ts

yarn w path/to/myScript.ts

yarn es is the same as node -r esbuild-register, it is running node using esbuild

yarn w is running the script using webpack

We use esbuild and webpack to be able to run any code in our monorepo, using typescript.

This causes a lot of trouble to detecting if a file is running as the entrypoint of a script or not.

How to check if a node file is running as a script?

We use !module.parent for node and esbuild, but we inject WEBPACK_ENTRY when using webpack, as we run the final webpack bundled code.

import path from 'path';

const cwd = process.cwd();

export const isMainScript = (require, module, filename: string) => {
  // webpack_entry is the real
  if (process.env.WEBPACK_ENTRY) {
    const fullEntry = path.join(cwd, process.env.WEBPACK_ENTRY);
    const fullFilename = path.join(cwd, filename);

    if (fullEntry === fullFilename) {
      return true;
    }

    return false;
  }

  if (!module.parent) {
    return true;
  }

  // eslint-disable-next-line
  console.log('not main script, check your script code');

  return false;
};
Enter fullscreen mode Exit fullscreen mode

In Conclusion

We need to detect if a file is running as script to avoid running the file script code if we are sharing some code.

Going deep in the rabbit hole, let us improve the DX of running scripts at Woovi


Woovi
Woovi is a Startup that enables shoppers to pay as they like. To make this possible, Woovi provides instant payment solutions for merchants to accept orders.

If you want to work with us, we are hiring!


Photo by Tianyi Ma on Unsplash

Top comments (0)