使用fs.readFileSync和buf.toString将html传递给js

时间:2015-06-23 08:18:10

标签: javascript html heroku

嗨我正在尝试使用buffers,toString和readFileSync将代码从我的html文件推送到我的javascript文件中。我有一个名为index.js的javacript文件和一个名为index.html的html文件。这是我网站上的错误:

https://secret-ocean-5221.herokuapp.com/

这是我的JS:

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

app.set('port', (process.env.PORT || 5000));
app.use(fs.static(__dirname + '/public'));

app.get('/', function(request, response) {
var buf = new Buffer(fs.readFileSync("index.html"), "utf-8");
response.send(buf.toString);
});

app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'));
});

我的HTML只是说:

Welcome to my site.

2 个答案:

答案 0 :(得分:0)

您没有调用toString方法,只是将其传入。更改为:

response.send(buf.toString());

另外,static是express的属性,而不是fs。

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

有了这个,假设你的index.html文件是公开的,你根本不需要fs.readFileSync。

调用readFile并使用节点回调以使其无阻塞也是更惯用的。

app.get('/', function(request, response, next) {
    fs.readFile("index.html", function (err, fileBuffer) {
        if (err) {
            return next(err); // Tell express to handle errors
        }
        response.send(fileBuffer.toString());
    });
});

答案 1 :(得分:0)

我发现了问题。 (1)我没有将我的html文件推送到我的github仓库 (2)我的代码错了,这里是正确的代码:

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

app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));

app.get('/', function(request, response) {
    fs.readFile('index.html', function(err, data){
    response.send(data.toString());
    });
});

 app.listen(app.get('port'), function() {
   console.log("Node app is running at localhost:" + app.get('port'));
});