2

I am just a beginner to nodejs and I came across the fs module. I tried to write a few lines of code.

var fs = require('fs'); 

// Open file demo.txt in read mode 
fs.open('/users/Upwn/desktop/ashok_pant.txt', 'r+', function (err, f) { 
  if(err) throw err; 
   console.log('Opened!'); 
}); 

The output was "Opened!" but nothing was opened from my local file system. What may be wrong with this?

3
  • 3
    what do you expect to happen? Commented Jun 2, 2020 at 11:23
  • @Ifaruki I think he expects the file to open on his operating system, as if you would have double clicked it. Commented Jun 2, 2020 at 11:34
  • stackoverflow.com/questions/29902347/… Commented Jun 2, 2020 at 11:59

2 Answers 2

3

If you want to open the file using the default OS application linked to the filetype, the following answer from Philipp Kief might be what you're looking for.

You can use the open module:

npm install --save open

and then call it in your Node.js file:

const open = require('open');
open('my-file.txt');

This module already contains the logic to detect the operating system and it runs the > default program that is associated to this file type by your system.

--- https://stackoverflow.com/a/61891139/1487756

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

1 Comment

But why did not the code I used work? In the official documentation and also in w3schools it is given as I have written.
0

If you want to read file content, please use readFileSync. Following is my code that I used before.

const fs = require('fs')
const path = require('path');
let content = JSON.parse(fs.readFileSync(path.join(__dirname, 'products.json')))
for (let line in content) {
    // do something
}

Comments

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.