NODE BITS

Random notes about Node JS.

Check if a file was executed from command line

If you have a js file, for using with Node JS, and you want to know if the file was run from the command line or required by a different js file, you can use require.main === module to check.

if(require.main === module) {
 // this file was executed by running `node ./this-file.js`
} else {
 // some other file required this file
}

Scary Node Command Line String Parse

Did you know - you can run any sketchy Node JS code directly from the command line, and have it execute?

Seems dangerous.

node -e "console.log(require('chalk').red('bro'))"

Execute Shell Command From Inside Node

The inverse from the last one. Run any command line command from inside of Node JS.

const { exec } = require('child_process');

const curlNowPlaying = () => {
  exec(`curl https://johnny.sh/api/currently-playing`, 
  (error, stdout, stderr) => {
    console.log({
          code: error && error.code ? error.code : 0,
          error,
          stdout,
          stderr,
        });
      },
    )
}

See Node Processes in Chrome

Useful chrome area → chrome://inspect/#devices

end of storey Last modified: