Ask coding questions

← Back to all posts
2
JavaScript fs.readFile function
ajayprashar (1)

Hi,
My name is Ajay and I am new to JavaScript. I have a question I was hoping you could help me with:

How do I access the function 'fs.readFile' from within node within repl.it?

import fs from 'fs';

let ourStuff = fs.readFile('G:\DATA\git\ipromise\ipromise.txt','utf8', callback);
console.log(ourStuff);

Thank you,
Ajay

Answered by eankeen (533) [earned 5 cycles]
View Answer
Commentshotnewtop
1
eankeen (533)

Hey!
So a more traditional way to import modules with node is by doing something like

let fs = require('fs');

If you want to do it like this:

import fs from 'fs';

You're going to have to pass in a particular flag (--experimental-modules) when running your app, which I don't think you can do with repl at the moment.

If you want to look into how to handle the data from reading the file, I'd recommend looking at this.

I'd also recommend looking into the differences between fs.readFile and fs.readFileSync - from the example you showed above, you might want to be using readfilesync instead.

Hope I was able to help =P

1
ajayprashar (1)

@eankeen Thanks for the great reply. I will try your advice right now.

1
ajayprashar (1)

@eankeen In appreciation of your reply, I thought I would provide an update.

As far as error messages go I adjusted my simple code as follows:

const fs = require('fs');

let ourStuff = fs.readFile('G:\\DATA\\git\\ipromise\\ipromise.txt','utf8', (err, data) => {
		if (err) throw err; 
	
		// Converting Raw Buffer to text 
		// data using tostring function. 
		console.log('#################'); 
		console.log(data); 
	})

It occurred to me that perhaps the backslashes were being misinterpreted as escape keys or escape sequences, so I doubled them up as I do in linux configuration files. This adjustment rid me of all the error messages. Partial success!!!

However, the code does seem to run locally using Node with good output, but it runs successfully with NO output on repl.it.

Should I assume that this is a security related issue?
-Ajay

1
eankeen (533)

@ajayprashar Hmm. I would not. Oversimplifying, repl.it runs their Node processes on Linux. And Linux uses forward slashes. I would consider using path.join() to ensure that it works both on your Windows machine and on replit. Something kind of like path.join(__dirname, 'ipromise.txt') instead of G:\\DATA...ipromise.txt.

To do this you need to import the path module

let path = require('path');

:)