Page 1 of 1

fs.readFile from local path in node.js

Posted: Mon Jan 10, 2022 4:45 pm
by bkromer
My Switch Server runs on Windows. I want to read a *.pdf locally to upload it later in a form data API Call.
I want to define a path to "C:/Users/username/Documents/Scripts/pdfsforupload/mypdf.pdf".
Is it correct to use this syntax?

Code: Select all

const file = fs.readFileSync(`//Users/username.domain/Documents/Scripts/pdfforupload/${fileName}`)

Does Switch have access to this folders or is it better to read it from a smb share?
And if I would read from ./ would this be the folder where the script is in or the installation folder of switch?

When I try to read a pdf file like that I get a UNKNOWN: unknown error, open '//Users/username.....

Outside of switch on my mac with Node.js v14.17.0. this works and I get the Buffer and filestream logged to the console.

Any hints?

Re: fs.readFile from local path in node.js

Posted: Mon Jan 10, 2022 5:31 pm
by jan_suhr
Try to use \\ between the folders

Re: fs.readFile from local path in node.js

Posted: Mon Jan 10, 2022 5:52 pm
by bkromer
Thanks double slashes worked "C://Users//.... :lol: "

Re: fs.readFile from local path in node.js

Posted: Mon Jan 10, 2022 6:10 pm
by freddyp
It is not the double slashes that worked, it was the C: at the beginning.

Windows paths can be written in Javascript using the POSIX-style forward slashes (double in front of a share name, single in between folders) or using the Windows-style backslashes but you must not forget the drive letter if you are not using a UNC path.

As to doubling the backslashes it depends on the characters that enclose the string. Inside strings enclosed by single or double quotes the backslashes must be doubled because there the backslash acts as an escape character. However, when the strings is enclosed by backticks (as in your example), the backslashes do not have to be doubled.