Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Express readFile html和replace string返回空白页_Node.js_Express - Fatal编程技术网

Node.js Express readFile html和replace string返回空白页

Node.js Express readFile html和replace string返回空白页,node.js,express,Node.js,Express,我正在使用Express中的fs.readFileAPI来读取html文件,我想替换html文件中的字符串,但它在客户端返回一个空白页。 我的目录结构是: // ===== directory ===== // rootDir dist/ index.html index.js package.json // ==== package.json ==== // { "name": "express", "version": "1.0.0", "main":

我正在使用Express中的
fs.readFile
API来读取html文件,我想替换html文件中的字符串,但它在客户端返回一个空白页。 我的目录结构是:

// ===== directory ===== //
rootDir
    dist/
        index.html
index.js
package.json

// ==== package.json ==== //
{
  "name": "express",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "private": true,
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "express": "^4.16.3"
  }
}

// ==== dist/index.html ======//
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Some Title</title>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>


// ==== index.js ==== //
const express = require('express');
const path = require('path');
const fs = require('fs');

const app = express();
const PORT = 3000;

app.use(express.static('dist'));

fs.readFile(path.resolve(__dirname, 'dist/index.html'), (err, data) => {
    if (err) throw err;
    const lorem = 'lorem ipsum';
    const test = data.toString().replace('<div id="app"></div>', `<div id="app">${lorem}</div>`)

    // doing console.log for testing
    console.log(test)

    // returning variable
    // return test
});

app.get('/', (req, res) => {
    res.render('index.html')
})

app.listen(PORT, (error) => {
    console.log(`listening port ${PORT}`);
})
没有错误,但为什么我有一个空白页?有什么建议或帮助吗


谢谢

发生这种情况是因为,当您执行
fs.readFile
时,您不会将结果存储在任何地方。当您
返回测试时,则该值不存在

要解决您的问题,请删除此无用的
fs.readFile
部分,并在路由器中指定'dist/index.html',如下所示:

// ==== index.js ==== //
const express = require('express');
const app = express();

const PORT = 3000;

app.use(express.static('dist'));

app.get('/', (req, res) => {
  res.render('dist/index.html');
});

app.listen(PORT, error => {
  console.log(`listening port ${PORT}`);
});
这应该行得通

// ==== index.js ==== //
const express = require('express');
const app = express();

const PORT = 3000;

app.use(express.static('dist'));

app.get('/', (req, res) => {
  res.render('dist/index.html');
});

app.listen(PORT, error => {
  console.log(`listening port ${PORT}`);
});