Search code examples
node.jsfileinstancefsinstance-variables

Node.js cant import File instance from local folder


I have a problem with importing any file as a file instance from local folder. Can you help me please? I can't find anything in 'fs' or 'path', maby because I don't know what to see I want to get File and pass it to my JS applicatin as a File instance.


Solution

  • Start by using a path relative to your script and the __dirname directive.

    fs.readFileSync(__dirname + '/myfile.txt')
    

    You may also wish to lose the / using path to make your code more portable.

    const path = require('path')
    fs.readFileSync(path.join(__dirname, 'myfile.txt')
    

    In regards to format, the result will be Buffer. If you want a string,

    fs.readFileSync(filename,'UTF-8')
    

    If you want a blob, see stackoverflow.com/questions/14653349