简体   繁体   中英

Read file using JSON

I am making an application using node.js with express.js, and instead of using JADE, I am using EJS (Embedded Javascript). When I send(response) information to be plugged into my template I usually send as JSON file, but sometimes I want the JSON file have big chunk of HTML code. This is what I have:

  1. JSON File
  2. index.js (to send response)
  3. blogPost.html

This is what I need:

  1. Get blog post into the JSON file
  2. Send it through index.js and make the server send the template with the HTML code...

I need:

{
    "title": "Test blog post",
    "paragraph": fs.readFileSync(blogPost.html)
}

replace the fs.readFileSync() with whatever I would use in JSON to read a file.

As per this answer , JSON is a data description language, not a programming language. Therefore, it is not possible to execute a function within JSON. I would execute the fs.readFileSync when the request is made to your server and include that data as a variable within the JSON model response itself. See this answer for more on that, although they're discussing it within the context of PHP, similar principles should apply. This blog post should help as well. Note the intricacy involved in making sure the proper characters are escaped and everything is formatted correctly.

EDIT

Here(validator.js) is a nice module to help with the html escaping/validation before you send it off with the rest of the JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM