fs.readFileSync无法读取nodejs中的文件传递路径变量 [英] fs.readFileSync Cannot read file passing path variable in nodejs
问题描述
我正在尝试使用fs读取xml文件.在将路径变量作为该函数的第一个参数传递后,我无法使用fs.readFileSync读取文件.注意:这是在Windows机器中
I am trying to read xml file using fs.I am not able to read file using fs.readFileSync after passing path variable as first paramter to this function. Note:this is in windows machine
xmlFile="C:\Users\xyz\AppData\Local\.proxySettings.xml";
function myFunc(xmlFile) {
let xmlData = fs.readFile(xmlFile);
alert(xmlData);//doesn't print anything
parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlData,"text/xml");
....
....
}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<proxy_port>2582</proxy_port>
更新文件
try{
ffile="jdkdkj";
fs.readFileSync(ffile);
}catch(err){
app.console.log(err);
}
Error { errno: -4058, syscall: 'open', code: 'ENOENT', path: 'jdkdkj' }
推荐答案
在JavaScript中,反斜杠字符用于表示紧随其后的字符应作特殊处理.为了在JavaScript字符串中创建文字反斜杠,您需要使用另一个反斜杠对反斜杠进行转义.
In JavaScript the backslash character is used to signal that the character immediately following it should be treated specially. In order to create a literal backslash inside a JavaScript string you need to escape the backslash with another backslash.
var a = "\abc";
console.log(a); // abc
var b = "\\abc";
console.log(b); // \abc
var c = "\"abc\"";
console.log(c); // "abc"
xmlFile="C:\\Users\\xyz\\AppData\\Local\\.proxySettings.xml";
console.log(xmlFile); // C:\Users\xyz\AppData\Local\.proxySettings.xml
因此,Windows路径名在JavaScript中始终需要双反斜杠
So, windows pathnames always need double backslashes in JavaScript
这篇关于fs.readFileSync无法读取nodejs中的文件传递路径变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!