Ask coding questions

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

Hi.

My name is Ajay and I am learning JavaScript using Repl.it.

When I use the code below I receive the error that 'fs.readFile' is NOT a function. Does anyone know how to use this function within repl.it?

import fs from 'fs';

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

https://repl.it/@ajayprashar/iPromise

Commentshotnewtop
TheDrone7 (592)

That shouldn't happen if you're using node.js. could you link is to a repl, just to go through what exactly you're trying to do?

TheDrone7 (592)

@ajayprashar instead of import fs from 'fs';
Try using const fs = require ('fs');
If it still doesn't work, try adding it using the package manager.

ajayprashar (1)

@TheDrone7 Thank you for your assistance. I did try what you mentioned but it still errors for me:

node v10.15.2 linux/amd64
   
evalmachine.<anonymous>:1
import fs from 'fs';
       ^^

SyntaxError: Unexpected identifier
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInContext (vm.js:284:10)
    at evaluate (/run_dir/repl.js:133:14)
    at ReadStream.<anonymous> (/run_dir/repl.js:116:5)
    at ReadStream.emit (events.js:189:13)
    at addChunk (_stream_readable.js:284:12)
    at readableAddChunk (_stream_readable.js:265:11)
    at ReadStream.Readable.push (_stream_readable.js:220:10)
    at lazyFs.read (internal/fs/streams.js:181:12)
TheDrone7 (592)

@ajayprashar as I said, use const fs = require ('fs'); which is the traditional JavaScript syntax instead of the new import statement that is not supported everywhere.

ajayprashar (1)

@TheDrone7 Hi! I wanted to bring this question to a close and thought I would provide an update.

I took your advice and modified the code to be more readable.

// Requiring fs module in which 
// readFile function is defined. 
const fs = require('fs');

// Reading data in utf-8 format 
// which is a type of character set. 
// Instead of 'utf-8' it can be 
// other character set also like 'ascii' 
fs.readFile('G:\\DATA\\git\\ipromise\\ipromise.txt', 'utf-8', (err, data) => {
	if (err) throw err; 

	// Converting Raw Buffer to text 
	// data using tostring function. 
	console.log('#################'); 
	console.log(data); 
}) 

I believe your comment regarding the first "const" line fixed a portion of it and I was also erroring on the fact that I need double backslashes "\" instead of single as singles were getting interpreted as escape sequences.

When I run the updated code on REPL.IT, it runs error free but with no output.

When I run the code locally using Node, it runs successfully with the expected output.

Is this normal? Security related?

-Ajay