Javascript插入反斜杠:uu dirname+&引用;index.html“;
在下面的问题中,有人给了我以下代码:Javascript插入反斜杠:uu dirname+&引用;index.html“;,javascript,Javascript,在下面的问题中,有人给了我以下代码: res.end(fs.readFileSync(__dirname + "index.html")); 但是,这将创建folderNameindex.html的文件名,即index.html之前需要有反斜杠。通过谷歌搜索,解决方案应该是双引号内的两个x,结果是“\index.html”。我尝试过这个和许多其他变体,单、双、高音、前斜杠、正则表达式转义。在任何情况下,我的CLI都告诉我它找不到folderNameindex.html文件 这可能很简单。谢谢
res.end(fs.readFileSync(__dirname + "index.html"));
但是,这将创建folderNameindex.html的文件名,即index.html之前需要有反斜杠。通过谷歌搜索,解决方案应该是双引号内的两个x,结果是“\index.html”。我尝试过这个和许多其他变体,单、双、高音、前斜杠、正则表达式转义。在任何情况下,我的CLI都告诉我它找不到folderNameindex.html文件
这可能很简单。谢谢你的帮助
编辑:
我的新代码:
const http = require('http'), // to listen to http requests
path = require('path'),
fullPath = path.join(__dirname, 'index.html'),
fs = require('fs'); // to read from the filesystem
const app = http.createServer((req,res) => {
// status should be 'ok'
res.writeHead(200);
// read index.html from the filesystem,
// and return in the body of the response
res.end(fs.readFileSync(fullPath)); });
app.listen(3000); // listen on 3000
我仍然会遇到同样的错误-我的命令行告诉我它找不到folderNameindex.html例如,您应该使用path.join
const path = require('path')
const fullPath = path.join(__dirname, 'index.html')
此外,还有许多其他函数可以帮助您以可移植的方式处理路径,请确保阅读和模块的所有文档。使用
path.join(\uu dirname,'index.html')
。您必须使用斜杠而不是反斜杠。还有一个斜杠,谢谢你,但还是没用。我已经用新代码编辑了我的问题。@emma你应该用res.sendFile(fullPath)
(或res.download(fullPath)
)替换res.end
行,看看文档;