如何使用Node.js读取文本文件并将其写入HTML页面? [英] How to read a text file with Node.js and write it to a HTML page?

查看:875
本文介绍了如何使用Node.js读取文本文件并将其写入HTML页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,我想使用fs模块与Node.js一起阅读.我知道如何读取文件,但不知道如何获取文本文件的数据并将其放置到网站页面上.

I have a text file that I would like to read with Node.js using the fs module. 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.

例如:我想读取一个文件,其中包含"hello world !!!"的内容.然后使用jQuery将其放入div.

For Example: I would like to read a file that has the contents of 'hello world!!!' and then using jQuery put it to a div.

推荐答案

NodeJS不是Web服务器.

但是,您可以轻松添加依赖项来提供 能力.

However, you can easily add dependencies to provide such capabilities.

例如 express koa hapi .

e.g. express, koa, or hapi.

到目前为止,您已经获得了[类似]:

So far, you've got [something like]:

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

您可以按以下方式使用 express (注意:如果没有 已经运行npm init,请这样做并提供合理的默认值):

You could use express as follows (note: if you have not already run npm init, do so and provide sensible defaults):

npm init 
npm install --save express

然后,创建一个文件app.js,以为您提供数据,例如:

Then, create a file, app.js, to serve you're data, e.g.:

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);

启动您的节点"Web服务器":

Launch your node "web server":

node app.js

最后,将浏览器指向:

http://localhost:5555/

这篇关于如何使用Node.js读取文本文件并将其写入HTML页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆