Not works fs.readFile in node js

后端 未结 5 802

I have:

 fs.readFile(\'../services/Prescipcion.xml\', \"utf8\", function (err, data) {
    console.log(\"err->\", err);
    console.log(\"data\", data);
 });
         


        
5条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-19 11:07

    you can use relative or absolute path as fs.readFile argument , but the point is that i got stumped with this was:

    if you have let path = 'c:\a\b\c.d and you want to use it as an arg for fs.readFile(path, {'utf-8'}, (err, content) => {//...your stuffs}) you should take care that \ is an escape character in js, so fs read your path as c:abc.d then it will use this path as a relative path so fs will search for C:\Users\dir_to_your_project\c:abc.d which is obviously not a valid path and it results in a Error: ENOENT: no such file or directory... error

    so how to fix this issue?

    it's very simple you should just replace \ with \\ in your desired path before using it as an arg in fs.readFile():

    new_path_for_fsReadFileArg = path.replace(/\\/g,"\\\\");
    

提交回复
热议问题