如何打印从node.js的变量HTML

时间:2019-02-02 18:38:27

标签: node.js

我试图从文本文件中获取随机文件并在我的HTML中打印出来。我在控制台中成功获取了该行,但是由于某些原因,即使我在routesjs文件中传递了变量,它也没有在屏幕上显示。任何帮助都非常感谢,谢谢!

routes / index.js

var express = require('express');
var router = express.Router();
var http = require('http');
var fs = require('fs');

var line;

function read(file, callback) {
    fs.readFile(file, 'utf8', function(err, data) {
        if (err) {
            console.log(err);
        }
        var lines = data.split("\n");

 //Random item number
 var r = Math.floor(Math.random() * lines.length);

 //Get random line
 var line = lines[r];

    console.log(line);


    });
}

var output = read('Input.txt', function(data) {

    var lines = data.split("/n");

    //Random item number
    var r = Math.floor(Math.random() * lines.length);

    //Get random line
    var line = lines[r];
    console.log("d;d;");

});

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', {page:'Home', menuId:'home', line: line});
});

router.get('/about', function(req, res, next) {
  res.render('about', {page:'About Us', menuId:'about'});
});

router.get('/contact', function(req, res, next) {
  res.render('contact', {page:'Contact Us', menuId:'contact'});
});

module.exports = router;

视图/ index.ejs

<!DOCTYPE html>
<html lang="en">
<head>
 <% include partials/head %>
</head>
<body>
<% include partials/menu %>

<div class="container-fluid bg-3 text-center">
  <h3><%= page %></h3><br>
  <div class="row">
    <div class="col-sm-4">
       // not printing anything 
      <p>your account info : <%= line %> </p>

    </div>
    <div class="col-sm-4">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>
    <div class="col-sm-4">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>
  </div>
</div>

</body>
<% include partials/script %>
</html>

1 个答案:

答案 0 :(得分:0)

var line = lines[r];是从外var line;

的函数的局部变量不同

尝试line = lines[r];

但是,我认为最好调用read()并在本地function(req, res, next) {中获取行。

添加:如果要同步读取文件,则应使用readFileSync