我无法让我的NodeJS服务器正确返回HTML文件所需的辅助文件。它没有将它们返回到文件中的适当位置,而是做了一些非常棘手的事情。
以下是相关代码:
index.js:
var http = require('http');
var url = require('url');
var fs = require('fs');
var path = require('path');
var findFile = (function(basename) {
var results = {
contentType: '',
data: ''
};
var dataCSS = {
dir: '../CSS/',
contentType: 'text/css'
};
var dataHTML = {
dir: '../HTML/',
contentType: 'text/html'
};
var dataJS = {
dir: '../JS/',
contentType: 'text/javascript'
};
return function(basename) {
switch (path.extname(basename)) {
case '.css':
fs.readFile(dataCSS.dir + basename, function(err, data) {
results = {
contentType: dataCSS.contentType,
data: data
};
});
break;
case '.html':
fs.readFile(dataHTML.dir + basename, function(err, data) {
results = {
contentType: dataHTML.contentType,
data: data
};
});
break;
case '.js':
fs.readFile(dataJS.dir + basename, function(err, data) {
results = {
contentType: dataJS.contentType,
data: data
};
});
break;
default:
fs.readFile(dataHTML.dir + 'Home.html', function(err, data) {
results = {
contentType: dataHTML.contentType,
data: data
};
});
break;
}
return results;
};
})();
http.createServer(function(req, res) {
var myUrl = url.parse(req.url);
var basename = path.basename(myUrl.path);
console.log('request url: ' + req.url);
if (req.url !== '/') {
console.log('File requested: ' + basename);
} else {
basename = "Home.html";
}
console.log("Basename: " + basename);
var data = findFile(basename);
console.log(data);
res.writeHead(200, { 'ContentType': data.contentType });
res.write(data.data);
res.end();
}).listen(8080);
Home.html中:
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href="../CSS/myApp.css">
<script src="../JS/myApp.js"></script>
<script src="../JS/myCtrl.js"></script>
</head>
<body>
<h2>myApp Test</h2>
<div class="myApp" ng-app="myApp" ng-controller="myCtrl" ng-init="quantity = 10; cost = 5" my-Directive>
<p>Color: <input type="text" style="background-color:{{myColor}}" ng-model="myColor" value="{{myColor}}"></p>
<p>Total in dollar (raw exp): {{quantity * cost}}</p>
<p>Total in dollar (span): <span ng-bind="quantity * cost"></span></p>
<p> First Name: <input type="text" ng-model="firstName"></p>
<p> Last Name: <input type="text" ng-model="lastName"></p>
<h1>Hello, {{firstName + " " + lastName}}</h1>
</div>
Are you even changing?!
</body>
</html>
我的代码的当前运行执行此操作:
Firefox中的开发窗口如下所示:
答案 0 :(得分:0)
f <- function(x) {
x
10
}
f(stop("This is an error!"))
是异步的,这意味着你给它的回调不会立即发生,它会在以后的某个时间发生。特别是,在fs.readFile
函数返回值后发生。 See this related question for more details.
为了使findFile
正常工作,只要findFile
操作完成,就需要接收回调函数。另请查看promises和async/await作为使用回调的更清晰的替代方法。
fs.readFile