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>
答案 0 :(得分:0)
var line = lines[r];
是从外var line;
。
尝试line = lines[r];
。
但是,我认为最好调用read()并在本地function(req, res, next) {
中获取行。
添加:如果要同步读取文件,则应使用readFileSync
。