有没有什么办法不用框架就可以让html和js代码分离,每写一句html都要用引号和加号忒麻烦. 怎样用nodejs读取一个html文件?readFile()?readFile的结果怎么返回到浏览器显示呢?
fs.readFile(file_path, "binary", function(err, file) { if (err) { response.writeHead(500, { 'Content-Type': 'text/plain' }); response.end(err); } else { response.writeHead(200, { 'Content-Type': 'text/html' }); response.write(file, "binary"); response.end(); } });
我现在的程序是这样的,file_path用绝对路径时可以正常返回数据,但用"./index.html"这个相对路径时,就异常关闭
var http = require("http"); http.createServer(function(request, response) { var file_path = "./index.html"; require("fs").readFile(file_path, "binary", function(err, file) { if (err) { response.writeHead(500, { 'Content-Type': 'text/plain' }); response.end(err); } else { response.writeHead(200, { 'Content-Type': 'text/html' }); response.write(file, "binary"); response.end(); } }); }).listen(8888); console.log("服务启动...");
@MiracleIT 你的 index.html 在哪个路径? .js 脚本在那个路径? 执行命令在哪个路径? 然后报错是啥?
index.html
.js
@MiracleIT
process.on('uncaughtException', function (err) { console.error(err.stack); });
用这个捕获一下错误,另外我还是推荐用express吧, restful,static file, gzip 还有好多东西都帮你做好了
@MiracleIT 你可以像这样找到index.html相对于本文件的路径 path.join(path.dirname(__dirname), ‘…/…/public/index.html’);
@jiyinyiyong 嗯 是执行路径的问题,把执行路径改成index.html的路径就可以了,有没有办法设置默认的执行路径
@MiracleIT 不懂… 照说 index.html 和 .index.html 完全一样的呀… 改路径的话, 对然不清楚你具体意思, 但用 filename dirname process.env.PWD这几个弄下绝对路径应该能做到的
.index.html
filename dirname process.env.PWD
CNode 社区为国内最专业的 Node.js 开源技术社区,致力于 Node.js 的技术研究。
我现在的程序是这样的,file_path用绝对路径时可以正常返回数据,但用"./index.html"这个相对路径时,就异常关闭
@MiracleIT 你的
index.html在哪个路径?.js脚本在那个路径? 执行命令在哪个路径? 然后报错是啥?@MiracleIT
用这个捕获一下错误,另外我还是推荐用express吧, restful,static file, gzip 还有好多东西都帮你做好了
@MiracleIT 你可以像这样找到index.html相对于本文件的路径 path.join(path.dirname(__dirname), ‘…/…/public/index.html’);
@jiyinyiyong 嗯 是执行路径的问题,把执行路径改成index.html的路径就可以了,有没有办法设置默认的执行路径
@MiracleIT 不懂… 照说
index.html和.index.html完全一样的呀… 改路径的话, 对然不清楚你具体意思, 但用filename dirname process.env.PWD这几个弄下绝对路径应该能做到的