node.jsnode.js-fs

Give file link in place of absolute path in fs.createReadStream();


I've a code like this

const fileData = fs.createReadStream('Google Sheet Link');

The error I am getting is this.

This is probably due to fs trying to read from an absolute path, rather than directly from the URL.

The path, it is taking is "Directory to which file is located" + "Google sheet link"

I only want to open google sheet link in the createReaderStream Path.

I've hidden the google sheet path due to privacy reasons.

enter image description here


Solution

  • The createReadStream() method is an inbuilt application programming interface of fs module which allow you to open up a file/stream and read the data present in it.

    fs.createReadStream( path, options )
    

    Parameters: This method accept two parameters as mentioned above and described below:

    Now, To avoid paths issues, it's recommended to use path.join, like:

    const path = require('path');
    
    const pathGoogleSheet = path.join(__dirname, 'Sheet name');
    const readableStream = fs.createReadStream(pathGoogleSheet);
    
    

    Here, you're creating a path to the google sheet referring to the current directory of the script stored in global variable called __dirname.