繁体   English   中英

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

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

我想在我的网页中显示我的index.html文件的内容

这是我在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');
    }

此代码在我的控制台中显示了我的 html 文件内容,但它不在我的服务器中。 页面不会停止加载。

编辑

我没有返回我的数据,我添加了reponse.send(data)并且它运行良好。

只需使用 res.sendFile 方法返回 html 页面即可,在这种情况下您实际上不需要使用 fs。

例子:

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

暂无
暂无

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

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