Nodejs -Unable to read text file having space in file directory

Viewed 4187

I am trying to read a file placed inside visuals studio 2017 projects folder. As there is a space in the file path,below code always return 'Error - File does not Exists'.I tried putting a double quotes around the path and replaces all spaces with %20.unfortunately both did not worked for me

Can some one help me to resolve it?

File Path -

C:/Users/Guest/Documents/Visual Studio 2017/Projects/help.txt

Code:

if (fs.existsSync(filePath)) {

        fs.readFile(filePath, 'utf8', function (err, contents) {
            if (err) {
                logger.error("Error while reading the file - " + filePath)
                next("Error while reading the file")
            } else {
                next(contents);
            }
        });
    } else {
        logger.error("File does not exist in path - " + filePath)
        next("Error - File does not Exists")
    }
1 Answers

Go to your directory C:/Users/Guest/Documents/ and execute dir /x command in console. you will get short-cut name for folder Visual Studio 2017, something like this:

02-11-2015  22:50    <DIR>          VISUAL~1     Visual Studio 2005
05-11-2015  20:40    <DIR>          VISUAL~2     Visual Studio 2008
27-01-2016  23:35    <DIR>          VISUAL~3     Visual Studio 2010
13-08-2017  00:42    <DIR>          VISUAL~4     Visual Studio 2012
04-02-2017  00:02    <DIR>          VI3A49~1     Visual Studio 2013
15-10-2017  02:06    <DIR>          VIDE5F~1     Visual Studio 2015

Use the short-cut name you want in file path while reading.

Another work-around is to escaping space character.

path = filePath.split(/\ /).join('\ ');
Related