Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to run a NodeJS script from an exported function via an "npm start" script defined in the package.json?

Problem

I have a script that worked by running node index.js. As I am attempting to emulate the structure of an AWS Lambda function, I moved the running logic of the code into a function defined as export async function handler(...) {. This function can be executed via the command line with the command node -e "import('./index.js').then(module => module.handler())".

Desired outcome

I would like to run the command: node -e "import('./index.js').then(module => module.handler())" by defining it in the npm scripts. Preferably it would be run by executing npm start.

Attempted Solutions

In package.json:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  ...
  "scripts": {
    "start": "...",
  },
  ...
}

Attempts were made with "start": "..." set to these, returned errors when executing:

  • "node -e 'import(\\'./index.js\\').then(module => module.handler())'"
  • "node -e 'import(\\'./index.js\\').then(function (module) { module.handler(); })'"
  • "node --eval='import(\\'./index.js\\').then(module => module.handler())'"
  • "node --eval='import(\\'./index.js\\').then(function (module) { module.handler(); })'"

Attempts made with these seemed to not evaluate:

  • "node -e 'import(\\'./index.js\\').handler()'"
  • "node --eval='import(\\'./index.js\\').handler()'"
  • "node -e 'require(\\'./index.js\\').handler()'"
  • "node --eval='require(\\'./index.js\\').handler()'"

I understand these above are redundant, I’m trying to be thorough. Any help would be much appreciated.

>Solution :

I would just create scripts/start.js

import { handler } from './index.js'
handler()

and then…

{
  ...
  "scripts": {
    "start": "node scripts/start.js"
  },
  ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading