Siddhartha Komodo
Siddhartha Komodo

Reputation: 221

fs.createReadStream is not finding file

I'm studying Node.js right now, using the "Beginning Node.js" textbook.

The example in the book does not execute properly in the command prompt. (I'm using Ubuntu 18.04 with Node v9.4.0, and the book is three years old, so this may be related?)

In the downloadable source code for the book, this is the code that is provided:

var fs = require('fs');

// Create readable stream
var readableStream = fs.createReadStream('./cool.txt');

// Pipe it to out stdout
readableStream.pipe(process.stdout);

The file, cool.txt, is in the parent directory.

--parentFolder

----jsFileToExecute.js

----cool.txt

When I run node jsFileToExecute.js in the command prompt, I get this response:

events.js:137
      throw er; // Unhandled 'error' event
      ^

Error: ENOENT: no such file or directory, open './cool.txt'

As this source code is directly from the textbook publisher's website and it still doesn't run, I'm assuming there's something wrong with it?

Looking for solutions to figure out why this isn't working. I've looked at the documentation at nodejs.org, but didn't find any clues.

Thank you for any help!

Upvotes: 7

Views: 18925

Answers (2)

Shamoon97
Shamoon97

Reputation: 329

if the file is in the same directory where currently you are running your project then you can simply type the name of the file instead of giving it the path like ./ or / like here:

var fs = require('fs');

// Create readable stream
var readableStream = fs.createReadStream('cool.txt');

// Pipe it to out stdout
readableStream.pipe(process.stdout);

It will work as will read the file from the same directory

Upvotes: 1

hsz
hsz

Reputation: 152206

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

const path = require('path');

const coolPath = path.join(__dirname, 'cool.txt');
const readableStream = fs.createReadStream(coolPath);

With above example, you're creating a path to the file referring to the current directory of the script stored in global variable called __dirname.

Upvotes: 22

Related Questions