0

I have a simple HTML file:

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Test of skill</title>
    <link rel="stylesheet" type="text/css" href="css/test.css">
  </head>
  <body>
  <div id="mydiv">y</div>

  </body>
</html>

I can use the following code to read it and assign the content to a string variable:

fs.readFile('./test-responsive.html','utf8', function(err, data){
    if(err) throw err;
    var myObj = {
        tpl: data
    };
}

The above code works great, but when I do the following, it doesn't work.

    var myObj2 = {
        tpl: " <!doctype html>
            <html>
                <head>
                    <meta charset="UTF-8">
                    <title>Test of skill</title>
                    <link rel="stylesheet" type="text/css" href="css/test.css">
                </head>
                <body>
                   <div id="mydiv">y</div>

                </body>
             </html> "
    };

I know it has something to do with line break and escaping, but how the line break works in the above two different situation? It would be great if you can explain the difference. Thank you!

why I don't need to escape or use "\" when reading from file to string?

Nicolas S.Xu
  • 13,794
  • 31
  • 84
  • 129
  • 1
    possible duplicate of [Creating multiline strings in JavaScript](http://stackoverflow.com/questions/805107/creating-multiline-strings-in-javascript) – Ben Fortune Aug 07 '14 at 09:37
  • You should also escape your speech marks in your HTML or wrap it with single quotes instead. – Ben Fortune Aug 07 '14 at 09:38
  • But why I don't need to escape or use "\" when reading from file to string? – Nicolas S.Xu Aug 07 '14 at 09:44
  • Because you're not manually creating the string, it's stored directly in a variable from the function. – Ben Fortune Aug 07 '14 at 09:45
  • when the function gets the string from the file, it does NOT need to be escaped, is because .... I am still struggling to understand this concept. Can you explain more? Thanks! – Nicolas S.Xu Aug 07 '14 at 09:55
  • 1
    fs.readFile automatically puts in the escaped new lines for you. – DF_ Aug 07 '14 at 09:58
  • @Deif, ahha.. now I can understand it... – Nicolas S.Xu Aug 07 '14 at 09:59
  • @Deif, how did you know about fs.readFile automatically puts in the escaped new lines? – Nicolas S.Xu Aug 07 '14 at 10:00
  • 1
    It's because they exist in the file already technically. When you manually paste the string as per your second example, there are no new lines (it will be interpreted as spaces instead) unless you explicitly state them. – DF_ Aug 07 '14 at 10:07

0 Answers0