NodeJS: Difference between revisions

896 bytes added ,  10 June 2020
Line 132: Line 132:
[https://www.npmjs.com/package/file-type-cli file-type-cli]<br>
[https://www.npmjs.com/package/file-type-cli file-type-cli]<br>
Detects the file type of a file or buffer
Detects the file type of a file or buffer
===argparse===
[https://www.npmjs.com/package/argparse argparse]
This is a port of python's argparse. However, it does not support configuration files. I usually use this snippet to parse configuration files:
<syntaxhighlight lang="python">
const parser = new ArgumentParser({
  version: "0.0.1",
  addHelp: true,
  description: "Description here"
});
// Add your arguments here
parser.addArgument(["--config"], {
  type: String,
  help: "Path to config file (optional)"
});
const args = (function() {
  let myArgs = parser.parseArgs();
  if (myArgs.config && myArgs.config.length > 0) {
    const filedata = fs.readFileSync(m_args.config, "utf8");
    const myArgsArr = filedata
      .split("\n")
      .filter(x => x.length > 0)
      .map(x => "--" + x)
      .map(x => x.split("="))
      .flatten();
    myArgs = parser.parseArgs(myArgsArr);
  }
  return myArgs;
})();
</syntaxhighlight>