【发布时间】:2017-05-11 04:32:11
【问题描述】:
我有一个文本文件,我想使用 Node.js 使用 fs 模块来阅读它。我知道如何读取文件,但我不知道如何获取文本文件的数据并将其放入网站页面。
例如:我想读取一个内容为“hello world!!!”的文件然后使用 jQuery 把它放到一个 div 中。
【问题讨论】:
标签: javascript jquery node.js
我有一个文本文件,我想使用 Node.js 使用 fs 模块来阅读它。我知道如何读取文件,但我不知道如何获取文本文件的数据并将其放入网站页面。
例如:我想读取一个内容为“hello world!!!”的文件然后使用 jQuery 把它放到一个 div 中。
【问题讨论】:
标签: javascript jquery node.js
我不知道这样做的目的是什么,但您可以使用 Express 启动一个简单的 Web 服务器,以提供您的文本文件的内容。然后,您只需要使用 jQuery 从您的网站页面请求此 Web 服务器。
【讨论】:
如果您使用 jquery 和 express,只需在您的 express 服务器上构建一个端点来提供文本文件的内容。
你的 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);
})
})
})
【讨论】:
据我了解,您希望在客户端而不是服务器上“呈现”文本。使用 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。
【讨论】:
NodeJS 不是网络服务器。
但是,您可以轻松添加依赖项来提供此类 能力。
例如express、koa 或 hapi。
到目前为止,您已经获得了 [类似]:
const 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,为您提供数据,例如:
const fs = require('fs');
const express = require('express');
const 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/
【讨论】:
const fs = require('fs');
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>
【讨论】: