'Is there any method to access local files and my program is on server node.js?

When I am executing this code on my local system its working fine. but when I am executing this code on server. It's not working.

try {
    var lineReader = require('readline').createInterface({
        input: require('fs').createReadStream('C:/sync/test.txt')
    });

    lineReader.on('line', function (localDirectory) {
        console.log('Line from file:', localDirectory);
    });
} catch (error) {
    console.error(error);
}


Solution 1:[1]

Location C:/sync/test.txt is in your pc.

I suggest you to put file in your project, example:

/your-project
   /files
     test.txt

index.js:

try {
    var lineReader = require('readline').createInterface({
                                         // create file path using __dirname
        input: require('fs').createReadStream(__dirname + '/files/test.txt')
    });

    lineReader.on('line', function (localDirectory) {
        console.log('Line from file:', localDirectory);
    });
} catch (error) {
    console.error(error);
}

Or use a env variable to define file location for different enviroments:

.env:

FILE_PATH=/path/to/file

index.js:

require('dotenv').config()
try {
    var lineReader = require('readline').createInterface({
        input: require('fs').createReadStream(FILE_PATH)
    });

    lineReader.on('line', function (localDirectory) {
        console.log('Line from file:', localDirectory);
    });
} catch (error) {
    console.error(error);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fiodorov Andrei