我有一个文本文件,我想使用fs模块与Node.js一起阅读。我知道如何阅读文件,但我不知道如何获取文本文件的数据,并能够将其放到网站页面。
例如:我想读一个内容为'hello world !!!'的文件然后使用jQuery将它放到div中。
答案 0 :(得分:2)
NodeJS不是网络服务器。
但是,您可以轻松添加依赖项以提供此类功能 能力。
e.g。 express
, koa
或 hapi
。
到目前为止,您已经[类似]:
var fs = require('fs');
fs.readFile('data.json', (e, data) => {
if (e) throw e;
console.log(data);
});
您可以按照以下方式使用 express
(注意:如果您还没有
已经运行npm init
,这样做并提供合理的默认值):
npm init
npm install --save express
然后,创建一个文件app.js
,为您提供数据,例如:
var express = require('express');
var app = express();
app.use('/', (req, res) => {
if (e) throw e;
// **modify your existing code here**
fs.readFile('data.json', (e, data) => {
if (e) throw e;
res.send(data);
});
});
app.listen(5555);
启动您的节点"网络服务器":
node app.js
最后,将浏览器指向:
http://localhost:5555/
答案 1 :(得分:0)
我不知道这是什么目的,但您可以使用Express启动一个提供文本文件内容的简单Web服务器。然后,您只需要使用jQuery从您的网站页面请求此Web服务器。
答案 2 :(得分:0)
如果您正在使用jquery并且表达只是在您的快速服务器上构建一个端点,该端点提供文本文件的内容。
你的jquery:
$.getJSON("/text", function(data){
<write code here to render contents of text file to the DOM>
})
节点中的结束点:
router.get("/text", function(req, res){
fs.readFile(textFile, 'utf8', function(err, data) {
if (err) throw err;
return res.json(textFile);
})
})
})
答案 3 :(得分:0)
据我所知,你想要在客户端“渲染”文本,而不是在服务器上。使用jQuery执行此操作的最简单方法是使用$.ajax
,如下所示:
const URL_TO_STATIC_TXT = 'https://cdn.rawgit.com/fabe/2a371ce28effb32fa1120f8d25225d37/raw/6d0bfebff1d0b52d72ed5ded4011a0bbff80d679/file.txt';
$.ajax({ url: URL_TO_STATIC_TXT })
.done(data => {
$('body').text(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
然后您只需要使用Node.js托管静态.txt
文件,甚至不使用fs
。使用Express,您可以使用app.use
:
app.use('/', express.static(__dirname + '/public'));
如果您想在服务器上呈现文件(使用fs
),您还可以查看无数的模板库,例如pug。