我计划学习如何使用Node.js建立自己的web服务器。我遵循了w3schools的Node.js教程,直到我进入了"Node.js文件系统“部分。(我知道,就在本教程的开头。)
任务是创建两个文件。
Http.createServer(函数(req,res) { fs.readFile('demofile1.html',函数(err,data) ){ res.writeHead(200,{‘Content’:‘text/html’};res.write(数据);res.end();}).listen(8080);
很简单,对吧?.js文件应该读取.html文件中的内容,并在浏览器中显示。
在同一教程的前面示例中,我刚刚用node whatever.js加载了node whatever.js,并在浏览器中使用localhost:8080运行脚本,但在本例中,chrome只是给了我一个“无法到达的站点(ERR_CONNECTION_REFUSED)”,它使node.js崩溃,并有以下错误:
_http_outgoing.js:642
throw new TypeError('First argument must be a string or Buffer');
^
TypeError: First argument must be a string or Buffer
at write_ (_http_outgoing.js:642:11)
at ServerResponse.write (_http_outgoing.js:617:10)
at ReadFileContext.callback (/home/eddo/nodejs_test/demo_readfile.js:6:9)
at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:420:13)我试图执行一个res.write(data.toString());但没有效果,并且将它更改为console.log(data);给了我一个控制台输出:
undefined
undefined但至少没有给我一个“这个网站无法到达(ERR_CONNECTION_REFUSED)”。
发布于 2018-08-05 23:04:14
你的花花公子都疯了:
fs.readFile('demofile1.html', function(err, data) {
节点在主目录而不是当前目录中查找'demofile1.html'。相反,使用
fs.readFile('./demofile1.html', function(err, data) {
或更好:
fs.readFile(__dirname + '/demofile1.html', function(err, data) {
https://stackoverflow.com/questions/51698823
复制相似问题