简体   繁体   English

如何使用 Node.js 读取文本文件并将其写入 HTML 页面?

[英]How to read a text file with Node.js and write it to a HTML page?

I have a text file that I would like to read with Node.js using the fs module.我有一个文本文件,我想使用 Node.js 使用 fs 模块读取它。 I know how to read the file but I do not know how to take the data of the text files and be able to put it to a website page.我知道如何读取文件,但我不知道如何获取文本文件的数据并能够将其放入网站页面。

For Example: I would like to read a file that has the contents of 'hello world!!!'例如:我想读取一个内容为 'hello world!!!' 的文件and then using jQuery put it to a div.然后使用 jQuery 把它放到一个 div 中。

NodeJS is not a web server. NodeJS 不是 Web 服务器。

However, you can easily add dependencies to provide such capabilities.但是,您可以轻松添加依赖项以提供此类功能。

eg express , koa , or hapi .例如expresskoahapi

So far, you've got [ something like ]:到目前为止,你已经有了 [类似的东西]:

const fs = require('fs');
fs.readFile('data.json', (e, data) => {
    if (e) throw e;
    console.log(data);
});

You could use express as follows ( note: if you have not already run npm init , do so and provide sensible defaults ):您可以使用express如下(注意:如果您还没有运行npm init ,请这样做并提供合理的默认值):

npm init 
npm install --save express

Then, create a file, app.js , to serve you're data, eg:然后,创建一个文件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);

Launch your node "web server":启动您的节点“网络服务器”:

node app.js

Finally , point your browser to:最后,将浏览器指向:

http://localhost:5555/

If you are using jquery and express just build an endpoint on your express server that serves the contents of the text file.如果您使用 jquery 和 express,只需在您的 express 服务器上构建一个端点,该端点提供文本文件的内容。

your jquery:你的jQuery:

$.getJSON("/text", function(data){
   <write code here to render contents of text file to the DOM>
})

your end point in node:您在节点中的端点:

router.get("/text", function(req, res){
      fs.readFile(textFile, 'utf8', function(err, data) {
        if (err) throw err;
        return res.json(textFile);
      })
    })
})

As I understand your question you want to "render" the text on the client, not on the server.据我了解您的问题,您想在客户端而不是服务器上“呈现”文本。 The easiest way to do this with jQuery is using $.ajax like this:使用 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>

Then you only need to host the static .txt files with Node.js, without even using fs .然后你只需要使用 Node.js 托管静态.txt文件,甚至不需要使用fs With Express you can achieve this with app.use :使用 Express,您可以通过app.use实现这app.use

app.use('/', express.static(__dirname + '/public'));

If you want to render the files on the server (using fs ) you can also look into countless templating libraries like pug .如果你想在服务器上渲染文件(使用fs ),你还可以查看无数的模板库,比如pug

I don't know what is the purpose of this, but you can use Express to start a simple web server that provide the content of your text file.我不知道这样做的目的是什么,但是您可以使用 Express 启动一个简单的 Web 服务器来提供您的文本文件的内容。 Then, you just need to request this web server from your website page using jQuery.然后,您只需要使用 jQuery 从您的网站页面请求此 Web 服务器。

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM