Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
Making a function to return whether the current code is being run directly or being imported, without using eval

Based on this it is possible for JS module code to determine whether it is being run directly or being imported from somewhere else. This is analogous to the old way of doing it but module is not a thing anymore in the EcmaScript Modules world? Or is it?

So, I wanted to take it a step further and use this as an opportunity to learn a few things under the hood.

I tried this

#!/usr/bin/env node
import url from "url";
const code = `
  console.error(
    "isScript debug: x:", import.meta.url, " y:", url.pathToFileURL(process.argv[1]).href
  );
  return import.meta.url === url.pathToFileURL(process.argv[1]).href;
`;
const f = Function(code);
export const isScript = () => f();

... as an attempt to not use eval which is "evil". Basically I want to be able to incorporate this logic in my scripts without having to write the import.meta.url === url.pathToFileURL(process.argv[1]).href code in each place that I need it. Because of two reasons, (1) it's just difficult to remember, and (2) making ridiculously tiny "libraries" is trendy with JS. But i realize that this may be challenging due to the "special" nature of import.

Indeed this code does not run: SyntaxError: Cannot use 'import.meta' outside a module

Is this a fool's errand? I could at least still make an isScript which has to receive an import.meta.url value, right? The thing is, that'd be a mildly ~leaky abstraction~ (not sure what term to use here) and rather unsatisfactory.

By the way, eval also does not work, the code "compiles" but when importing this module and trying to run it, I get SyntaxError: Cannot use 'import.meta' outside a module from the importing code. I might be doing something silly though.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!