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?

snowfrogdev
  • 5,963
  • 3
  • 31
  • 58

2 Answers2

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

Community
  • 1
  • 1
Moritz Roessler
  • 8,542
  • 26
  • 51
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
}
WebDev
  • 587
  • 1
  • 6
  • 23