[英]Node.JS - Filename won't accept a variable
不起作用:
console.log(obj.html_template); // outputs "myfile.html"
var html = fs.readFileSync(JSON.stringify(obj.html_template)); // file not found.
作品:
console.log(obj.html_template); // "myfile.html"
var html = fs.readFileSync("myfile.html"); // Works.
我要疯了。
> JSON.stringify('myfile.html')
""myfile.html""
您的代码正在文件系统中寻找文件"myfile.html"
(注意多余的引号)。 它不存在。
只需不加分类地查找即可:
var html = fs.readFileSync(obj.html_template);
调用JSON.stringify
,它将所有字符串转换为JSON格式的字符串,并带有双引号。 引用ECMAScript 5.1 JSON.stringify
规范 ,
如果
Type(value)
为String
,则返回调用带有参数value的抽象操作Quote
的结果。
此处定义了Quote
操作,该操作基本上用"
包围字符串,并照顾字符串中的特殊字符。
所以JSON.stringify
转换,字符串,例如, abcd.txt
到"abcd.txt"
,类似这样的
console.log(JSON.stringify("abcd.txt"));
// "abcd.txt"
这不等于abcd.txt
。
console.log(JSON.stringify("abcd.txt") == "abcd.txt");
// false
但等于"abcd.txt"
。
console.log(JSON.stringify("abcd.txt") == '"abcd.txt"');
// true
因此,您的程序将搜索名为"abcd.txt"
的文件,而不是abcd.txt
。 这就是为什么它找不到文件并失败的原因。
要解决此问题,只需删除JSON.stringify
并直接传递字符串,就像这样
var html = fs.readFileSync(obj.html_template);
为什么首先使用JSON.stringify
? 你应该能够做到
var html = fs.readFileSync(obj.html_template);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.