简体   繁体   English

fs readFile 在控制台中工作但不在服务器 Node.js

[英]fs readFile working in console but not in server Node.js

I want to show the content of my index.html file in my webpage我想在我的网页中显示我的index.html文件的内容

Here is my code in server.js这是我在server.js中的代码

  var express = require('express')()
const fs = require('fs');

express.get('/', (request, reponse) => {

    const path = './index.html';

    console.log(path);

    if (fs.existsSync(path)) {
        fs.readFile('./index.html', "utf8", (err, data) => {
            if (err) {
                console.log(err);
            }
            console.log(data);
        })
    }
    else {
        console.log('nope');
    }

This code shows my html file content in my console, however it doesn't in my server.此代码在我的控制台中显示了我的 html 文件内容,但它不在我的服务器中。 The page doesn't stop loading.页面不会停止加载。

EDIT编辑

I wasn't returning my data, I added reponse.send(data) and it works perfectly.我没有返回我的数据,我添加了reponse.send(data)并且它运行良好。

Just use res.sendFile method to return the html page, you actually don't need to use fs in this scenario.只需使用 res.sendFile 方法返回 html 页面即可,在这种情况下您实际上不需要使用 fs。

Example:例子:

router.get('/', (req,res) => {
   res.sendFile('home.html');
});

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

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