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.
-
1Creating multiline strings in JavaScriptRobert Harvey– Robert Harvey2015年02月25日 20:37:45 +00:00Commented Feb 25, 2015 at 20:37
-
Yeah, I've read that. I'm just not quite satisfied with any of those answers. Right now, I'm just putting the query in a separate plain-text file, and loading it into the variable via the fs module.Lonnie Best– Lonnie Best2015年02月27日 19:53:50 +00:00Commented Feb 27, 2015 at 19:53
-
I think that's about the best you're gonna get in Javascript.Robert Harvey– Robert Harvey2015年02月27日 20:51:12 +00:00Commented Feb 27, 2015 at 20:51
-
Yeah, I'll use this technique until ECMAscript 6. The desired feature is coming: nczonline.net/blog/2012/08/01/…Lonnie Best– Lonnie Best2015年02月27日 22:12:24 +00:00Commented Feb 27, 2015 at 22:12
-
This article addresses exactly what I'm looking for (coming in ECMA 6).Lonnie Best– Lonnie Best2015年04月02日 06:16:34 +00:00Commented Apr 2, 2015 at 6:16
1 Answer 1
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
-
Did you read my comments above (from 2015)?Lonnie Best– Lonnie Best2018年08月20日 06:13:38 +00:00Commented Aug 20, 2018 at 6:13