fs.readFile from local path in node.js

Post Reply
User avatar
bkromer
Member
Posts: 96
Joined: Thu Jul 11, 2019 10:41 am
Location: Germany

fs.readFile from local path in node.js

Post by bkromer » Mon Jan 10, 2022 4:45 pm

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?
Benjamin Kromer

jan_suhr
Advanced member
Posts: 491
Joined: Fri Nov 04, 2011 1:12 pm
Location: Nyköping, Sweden

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

Post by jan_suhr » Mon Jan 10, 2022 5:31 pm

Try to use \\ between the folders
Jan Suhr
Color Consult AB
Sweden
=============
Check out my apps

User avatar
bkromer
Member
Posts: 96
Joined: Thu Jul 11, 2019 10:41 am
Location: Germany

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

Post by bkromer » Mon Jan 10, 2022 5:52 pm

Thanks double slashes worked "C://Users//.... :lol: "
Benjamin Kromer

freddyp
Advanced member
Posts: 726
Joined: Thu Feb 09, 2012 3:53 pm

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

Post by freddyp » Mon Jan 10, 2022 6:10 pm

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.

Post Reply