Node.js – Preserving Pre-formatted Multi-Line Strings in Scripts

javascriptnode.jsPHPsql

There is a lot I don't like about PHP, but one thing I love is multi-line strings:

$query = <<<EOT
select
     field1
    ,field2
    ,field3
from tableName
where
    field1 = 123
EOT;

What's cool about this, is that I can just copy SQL, that I've hand formatted (to my liking) from a querying tool (like dbeaver), and paste it (with formatting and all) directly into a php script, without worry about how line-breaks might corrupt the script.

There's a lot I love about Javascript, but there doesn't seem to be a reliable equivalent that would allow you to copy and paste a pre-formatted SQL statement into a variable-value (with this same ease — and preserving the formatting).

I'm currently working on some small node.js projects and I'm very much missing this php feature.

The only think I can think to do, is to put my queries into a plain text file and import the formatted query from a file into the variable value. Then, later, when I need to modify the query, I can copy and paste to that file (pre-formatted) and then the script will just load my modifications next run.

However, sometimes I need certain parts of the query to be dynamical generated. In PHP, I could put variables into the multi-line string for such requirements. With this separate file idea (in Javascript), it seems more complicated; I'd have to make custom place-holders in the plain text file that are to be replace by the main script later. That seems like I might be reinventing a wheel that is already made. So that's why I'm posting here for advice.

I've read other post that have hacks for doing this type of thing in-script, but each solution doesn't match the ease and reliability of php's built-in support for such requirements.

Best Answer

JavaScript now supports multi-line strings via the backtick sytax. For example:

const foo = `$query = <<<EOT
select
     field1
    ,field2
    ,field3
from tableName
where
    field1 = 123
EOT;`

References