我想从文本文件中随机打印一行。我正在读取文本文件并从中返回一个随机行。我将它传递给res.send(),但它并没有显示在屏幕上。但它显示在日志文件中。关于这里出了什么问题的任何想法?
这是我正在运行的javascript代码:
var express=require('express');
var app=express();
var port = process.env.PORT || 3000
app.get('/', function (req, res) {
res.send(getRandomLine('listofquestions.txt'));
})
/*--------------------Routing Over----------------------------*/
function getRandomLine(filename){
var fs = require('fs');
fs.readFile(filename, function(err, data) {
if(err) throw err;
var array = data.toString().split("\n");
var length = Math.floor(Math.random() * array.length) + 1 ;
console.log(array[length]);
return (array[length]);
});
}
app.listen(port, function () {
console.log(`Server listening on port ${port}!`)
});
这是我用来阅读的文件:
What is possible?
What if it works out exactly as you want it to?
What is the dream?
What is exciting to you about this?
What is the urge?
What does your intuition tell you?