1

I have just started learning Node.js and was wondering if I misunderstood the code's intent,I thought the code shown below will print 'file opened' in the terminal or command prompt only when I open that text file but after I initiated the Node.js file, 'file opened' already appeared before opening the text file.

var fs = require('fs');
var readStream = fs.createReadStream('./new1.txt')
readStream.on('open', function(){console.log("file opened")})
4
  • What exactly do you mean when you say "When I open that text file"? Commented Feb 25, 2018 at 14:57
  • when i double clicked "new1.txt" in my folder Commented Feb 25, 2018 at 15:03
  • I thought so. That's not how it works. node.js can not see what other programs on your computer do, or where you double click, or anything of that kind. Can you explain what you actually want to do? Commented Feb 25, 2018 at 15:05
  • I just want to understand what the 'open' event mean Commented Feb 25, 2018 at 15:09

1 Answer 1

2

Let's go step by step so you can understand what's going on with your code and how Node.js works.

Here you will import the filesystem module into your code

var fs = require('fs');

Then you're using the createReadStream method from fs. Basically, it will create a readable stream object. You can get more info here

var readStream = fs.createReadStream('./new1.txt')

Finally, you need to know that Node.js is event-driven. It means that you can know when something is done "Let me know when it's ready" In this case, you're listening to the event 'open' so whenever ReadStream open the file (in your case new1.txt) it will let you know. The 'open' event doesn't mean that you need to open the file manually.

readStream.on('open', function(){console.log("file opened")})

Sign up to request clarification or add additional context in comments.

1 Comment

what is difference between open and read?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.