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:

{
  ...
  "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"
  },
  ...
}

Leave a Reply