Node.JS – 文件名不会接受一个variables

不起作用:

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 ,它会把所有的string转换成JSON格式的string,用双引号括起来。 引用JSON.stringify ECMAScript 5.1规范 ,

如果Type(value)String ,则返callback用具有参数的抽象操作Quote的结果。

这里定义了Quote操作,它基本上围绕着string"并且处理string中的特殊字符。

因此, JSON.stringify将string(例如JSON.stringify转换为"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 

所以,你的程序search一个名为"abcd.txt"而不是abcd.txt 。 这就是为什么它无法find文件并失败。

要解决这个问题,就直接删除JSON.stringify并传递string,像这样

 var html = fs.readFileSync(obj.html_template); 
 > JSON.stringify('myfile.html') ""myfile.html"" 

您的代码正在查找文件系统中的文件"myfile.html" (注意多余的引号)。 它不存在。

只要find它没有stringify:

 var html = fs.readFileSync(obj.html_template); 

你为什么首先使用JSON.stringify ? 你应该能够做到

 var html = fs.readFileSync(obj.html_template);