做个小测试: nodejs项目目录结构 nodetest/ index.js handle.js package.json public/template.html
var http = require('http');
var handler=require('./writeResponse');
http.createServer(function (request, response) {
response.writeHeader(200,{'Content-Type':'text/html'});
handler.writeResponse(response);
}).listen(3000);
console.log('Server is Start!');
![writeResponse.js]
var fs = require('fs');
function writeResponse(res) {
var temfile = './public/template.html';###注意这里的路径
fs.exists(temfile, function (exist) {
if (exist == true) {
fs.readFile(temfile, {'encoding': 'utf8', 'flag': 'r'}, function (err, data) {
data = data.replace(/{title}/g, 'This is Index Page![from template]');
res.write(data);res.end();
});
} else {
res.write('<h1>This is Error Page!'+temfile+'</h1>');
res.end();
}
});
}
exports.writeResponse = writeResponse;
![package.json]
{
"name": "nodetest",
"version": "0.0.1",
"main":"/index.js"
}
\n```
![问题是在nodetest目录下:”node index.js“程序运行良好
在nodetest上层目录运行:“node nodetest” fs读取未能读取public/template.html文件。
请问含有package.json的文件包,包内的代码如何编码才能确保路径的正确?]我是新手,Why