1

I recently found a npm package called syntax-checker (https://www.npmjs.com/package/syntax-checker)

And i would like to integrate this into my js script. I'm using a Discord chat bot which checks the message for a code block and the coding language. As the description of Syntax checker says, it supports Ruby, PHP, Perl, Lua, C/CPP, Bash, Javascript and Python. How would i integrate this into the bot? I currently use for js checking this script

  if (message.content.includes("```js"))
  {

    let code = message.content.substring('```js '.length);
    var codebegin = code.split("```js").pop();

    var n = codebegin.indexOf('```');
    var codeend = codebegin.substring(0, n != -1 ? n : codebegin.length);

    var check = require('syntax-error');

    var err = check(codeend);

    if (err)
    {

      message.reply("Your code contains errors! ```" + err + "```");
    }
    else
    {
message.reply("No Errors!");
    }

  }
Select
  • 93
  • 1
  • 11
  • just a little note on this, if someone were to write something then \`\`\`js // code \`\`\` it would break your string extraction code. – macdja38 Apr 24 '17 at 12:08

1 Answers1

1

Syntax-checker works by running the program on your computer used to compile code (with no output) and checking to see if there are any errors. It runs by analyzing every file in a directory passed in to it and then outputting to a file. You'll need to create a temporary file for each request then run the program using shell (look into child_process or exec for this).

All that module does ultimately is decide what language the code is from its file extension and run something like exec('php -l file/path/here.php', callbackFunctionHere). That's what it runs for PHP, the others are ruby -c, python -m py_compile, perl -c, luac -p, bash -n. gcc -fsyntax_only, and uglifyjs -o /dev/null.

With that knowledge, there's no sense in messing around with the file system whatsoever. Just use something like exec("echo '" + codeStr + "' | php -l', callbackFunctionHere);. Replace php -l with whichever linter you need. Make sure you escape any single quotes that might occur in the codeStr since you'll end up with odd errors otherwise.

Community
  • 1
  • 1
Peter G
  • 2,773
  • 3
  • 25
  • 35