How to use Node.js to build pages that are a mix between static and dynamic content?

前端 未结 7 1064
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 23:02

All pages on my 5 page site should be output using a Node.js server.

Most of the page content is static. At the bottom of each page, there is a bit of dynamic conten

相关标签:
7条回答
  • 2020-12-07 23:27

    First deliver only static HTML files from server to the client. Then use something like AJAX / server.io to serve the dynamic content. IMO Jade is really ugly for writing HTML code and its better to use a template engine.

    I did some Google and found some code by this fellow, its good if you are doing it for PoC / learning.

    var server = require('./server'); 
    var controller = require("./controller"); 
    var urlResponseHandlers = require("./urlResponseHandlers");   
    
    var handle = {};   
    handle["/"] = urlResponseHandlers.fetch; 
    handle["/fetch"] = urlResponseHandlers.fetch; 
    handle["/save"] = urlResponseHandlers.save;   
    server.start(controller.dispatch, handle); 
    

    Here is how the logic for handling URLs is displayed -

    var staticHandler = require('./staticHandler');
    
    function dispatch(handler, pathname, req, res) {
      console.log("About to dispatch a request for " + pathname);
      var content = "Hey " + pathname;
      if (typeof handler[pathname] === 'function') {
          content += handler[pathname](req);
          res.writeHead(200, {
              'Content-Type': 'text/html'
          });
          res.write(content);
          res.end();
      } else {
          console.log("No request handler found for " + pathname);
          staticHandler.handleStatic(pathname, res);
      }
    

    }

    Here is how static files can be handled -

    function handleStatic(pageUrl, response) {
        var filename = path.join(process.cwd(), pageUrl);
        path.exists(filename, function (exists) {
            if (!exists) {
                console.log("not exists: " + filename);
                response.writeHead(404, {
                    'Content-Type': 'text/html'
                });
                response.write('404 Not Found\n');
                response.end();
                return;
            }
            //Do not send Content type, browser will pick it up. 
            response.writeHead(200);
            var fileStream = fs.createReadStream(filename);
            fileStream.on('end', function () {
                response.end();
            });
            fileStream.pipe(response);
            return;
        });
    }
    exports.handleStatic = handleStatic;
    

    I liked the idea. All code copied from this link! .

    0 讨论(0)
  • 2020-12-07 23:31

    A solution have found to this, without using any other modules and or other script is to make the calling script into a module and include it with the function require().
    With this solution I can use javascript which ever way I want
    What I would do is make an ajax call to a nodejs script (www.example.com/path/script.js)
    script.js would need to be built like a module with the exports.functionName=function(){...}
    After that include it in your webserver function require(pathToTheScript).functionName(res,req)
    You will also need to end the response in the functionName(res,req) by doing res.end();

    0 讨论(0)
  • 2020-12-07 23:35

    One of the best things I found is to use NodeJS, Express and Mustache...

    You can create your HTML pages as you normally would using Mustache syntax for placeholders for your variables {{name}}...

    When a user hits your site, express routs the slug to the correct template... NodeJS get's the file... NodeJS get's the dataset from a DB... Run it through Mustache on the server... Send the completed page to the client...

    Here is a scaled back version I wrote on my blog. It's simple but the idea is pretty sound. I use it to quickly deploy pages on my site.

    http://devcrapshoot.com/javascript/nodejs-expressjs-and-mustachejs-template-engine

    I went this route because I didn't want to learn all of the extra syntax to write a language I already knew (html). It makes more sense and follows more of a true MVC pattern.

    0 讨论(0)
  • 2020-12-07 23:36

    These days the answer is not so straightforward.

    If you don't need to be indexed by Google, consider making a single-page application using socket.io and client-side templates such as jQuery Templates. There are even emerging node.js frameworks for this type of architecture, e.g. socketstream.

    If you need to be indexed by Google, do you need your dynamic content to be indexed? If yes, consider using express and server-side templates such as ejs, jade or mustache. Another (discouraged) approach might be to generate XML from JSON on server and use an XSLT front-end.

    If you need only static content to be indexed, consider using express on server, but don't generate any dynamic HTML on server. Instead, send your dynamic content in JSON format to client using AJAX or socket.io, and render it using client-side templates such as jQuery Templates.

    Don't consider server-side DOM: DOM doesn't scale for complex layouts, you will sink in a sea of selectors and DOM calls. Even client-side developers understood that and implemented client-side templates. A new promising approach is weld library. It offers best of both worlds, but it is not mature yet to be used in production (e.g. simple things like conditional rendering are not supported yet).

    0 讨论(0)
  • 2020-12-07 23:37

    Personally, I'd use a server that has higher level constructs. For instance, take a look at the expressjs framework - http://expressjs.com/

    The constructs you'll be interested in from this package are:

    • Truly static files (assets etc): app.use(express.static(__dirname + '/public'));
    • A templating language such as jade, mustache, etc:
      • http://expressjs.com/en/guide/using-template-engines.html
      • https://github.com/visionmedia/jade/
      • You'll want to look up 'locals' and 'partials' for embedding small bits of dynamic content in mostly static content

    For example in jade:

    !!! 5
    html(lang="en")
      head
        title= pageTitle
        script(type='text/javascript')
          if (foo) {
             bar()
          }
      body
        h1 Jade - node template engine
        #container
          - if (youAreUsingJade)
            p You are amazing
          - else
            p Get on it!
    

    Becomes:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <title>Jade</title>
        <script type="text/javascript">
          if (foo) {
            bar()
          }
        </script>
      </head>
      <body>
        <h1>Jade - node template engine</h1>
        <div id="container">
          <p>You are amazing</p>
        </div>
      </body>
    </html>
    

    If you prefer something a little less drastic I would say look at mustache or one of the other engines that looks a bit more like regular-sauce html.

    0 讨论(0)
  • 2020-12-07 23:44

    One good way is to use a templating engine. You can store the templates as separate files, and the templating engine has the ability to make the content dynamic. Personally I use yajet (http://www.yajet.net/) which is written for the web but works fine with node, and there are numerous template engines for node on npm.

    0 讨论(0)
提交回复
热议问题