fs.readFile from local path in node.js

Post Reply
bkromer
Member
Posts: 99
Joined: Thu Jul 11, 2019 10:41 am

fs.readFile from local path in node.js

Post 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?
Benjamin
jan_suhr
Advanced member
Posts: 586
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 »

Try to use \\ between the folders
Jan Suhr
Color Consult AB
Sweden
=============
Check out my apps
bkromer
Member
Posts: 99
Joined: Thu Jul 11, 2019 10:41 am

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

Post by bkromer »

Thanks double slashes worked "C://Users//.... :lol: "
Benjamin
freddyp
Advanced member
Posts: 1008
Joined: Thu Feb 09, 2012 3:53 pm

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

Post 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.
Post Reply