Reading a .txt file with NodeJS using FS - node.js

I'm trying to use NodeJS to read a txt file by using fs. This is the code of app.js:
var fs = require('fs');
function read(file) {
return fs.readFile(file, 'utf8', function(err, data) {
if (err) {
console.log(err);
}
return data;
});
}
var output = read('file.txt');
console.log(output);
When i do:
node app.js
It says
undefined
I have fs installed and there is a file.txt in the same directory, why is it not working?

Your read function is returning the result of the fs.readFile function, which is undefined because it doesn't have a return clause (it uses callbacks). Your second return clause is in an anonymous function, so it only returns to that scope. Anyhow, your function knows its finished after that first return.
The standard way to use fs.readFile is to use callbacks.
var fs = require('fs');
function read(file, callback) {
fs.readFile(file, 'utf8', function(err, data) {
if (err) {
console.log(err);
}
callback(data);
});
}
var output = read('file.txt', function(data) {
console.log(data);
});

Related

I get an error in fileSystem module while using writeFile Asynchronously

I'm trying to use writeFile() inside call back function of readFile() from fileSystem module..
I'm a beginner in node.js I have been watching Youtube tutorials
const fs = require('fs');
fs.readFile('readMe.txt','utf8', function(err, data){
fs.writeFile('writeMe.txt', data);
});
console.log('Fire..');
I get an error pasted below.. I don't understand the type of this error.. can someone help me with this?
Fire..!
fs.js:128
throw new ERR_INVALID_CALLBACK();
^
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
at maybeCallback (fs.js:128:9)
at Object.writeFile (fs.js:1163:14)
at C:\Users\shahzaib laptops\Desktop\NodeJS\pathModule\fileSystem.js:6:6
at FSReqWrap.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:53:3)
You can use the Following snippet to read and write file what need. You this in common and use this if u need in many place. u need to pass the filename to read and write to this method.
Else directly use the callback alone the parameter in method and jsut give the file name static as u have above.
public ReadandWriteFile(fileNameToRead, fileNameToWrite, callback) {
fs.readFile(fileNameToRead, "utf-8", (err, data) => {
if (err) { console.log(err) }
if (data) {
fs.writeFile(fileNameToWrite, data, (err) => {
if (err) { console.log(err) };
if (data) {
callback({ message: 'Successfully Written to File.' })
}
});
}
})
}
Add proper err handling and callback Fn. in writefile
const fs = require('fs');
fs.readFile('readMe.txt','utf8', function(err, data){
if(err) callback or return err
else{
fs.writeFile('writeMe.txt', data,'utf8', function(err2, data2){
if(err2) callback or return err2
else console.log(data2)
});
}
});
console.log('Fire..');
You can use promise for readFile and writeFile.
const fsPromises = require("fs").promises;
async function readAndWrite() {
let filehandle;
try {
filehandle = await fsPromises.readFile("readMe.txt");
console.log(filehandle);
let writeComleted = await fsPromises.writeFile("writeMe.txt", filehandle);
} catch {
throw new Error("something bad happened");
}
}
readAndWrite();

how to fix this error TypeError [ERR_INVALID_CALLBACK]: Callback must be a function

I am a beginner to the nodejs. When I type the below, the code error occurs like this:
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
var fs = require('fs');
fs.readFile('readMe.txt', 'utf8', function (err, data) {
fs.writeFile('writeMe.txt', data);
});
Fs.writeFile() according to the documentation here takes (
file, data[, options]and callback ) params so your code will be like this :
var fs = require('fs');
fs.readFile('readMe.txt', 'utf8', function (err, data) {
fs.writeFile('writeMe.txt', data, function(err, result) {
if(err) console.log('error', err);
});
});
fs.writeFile(...) requires a third (or fourth) parameter which is a callback function to be invoked when the operation completes. You should either provide a callback function or use fs.writeFileSync(...)
See node fs docs for more info.
Since node 10, it is mandatory to pass a callback on fs.writefile()
Node.js documented the purpose for the change: https://github.com/nodejs/node/blob/master/doc/api/deprecations.md#dep0013-fs-asynchronous-function-without-callback
You could add an empty callback like this fs.writeFile('writeMe.txt', data, () => {})
you also use like this
var file2 = fs.readFileSync("./Public/n2.jpeg")
You simply could use the sync function
var fs = require('fs');
fs.readFileSync('readMe.txt', 'utf8', function (err, data) {
fs.writeFileSync('writeMe.txt', data);
});
or use callback function
you can import the fs module from the fs/promises as they are promise-fied version of the modules so we don't need to use the callback function unnecessarily.
import fs from 'fs/promises';
fs.readFileSync('readMe.txt', 'utf8', function (err, data) {
fs.writeFileSync('writeMe.txt', data);`});`
var fs = require('fs');
fs.readFile('readme.txt', 'utf8', function(err, data) {
fs.writeFile('writemeee.txt', data, function(err, result) {
if (err) console.log('error', err);
});
});
try this .I have written the code using Promises.
const {readFile} = require('fs');
const {writeFileSync} = require('fs');
const readText = (path)=>{
return new Promise((resolve,reject) => {
readFile(path,'utf8',(err,result)=>{
if(err)
reject(err);
else
resolve(result);
})
})
}
readText('./contents/sample.txt')
.then(val=>writeFileSync('./results.txt',val))
.catch(err=>console.log(err));
This error hit me in the face when I was doing the following;
var hello = myfunction( callme() );
rather than
var hello = myfunction( callme );

node.js reading null string at the end of file

I am trying to read and print file in Node.js(6.10.2) but it prints a null string at the end
var fs = require('fs');
fs.readFile('aaa.xml', 'utf-8', function (data, err) {
if(err) console.log(err);
console.log(data);
});
It is working fine when I print with Python. What could the reason be?
You have reversed the data and the err in the callback function. So, the data was in the err variable and the err was in the data variable.
This should work fine
var fs = require('fs');
fs.readFile('aaa.xml', 'utf-8', function (err,data){
if(err) console.log(err);
console.log(data);
});
For more details refer to:
https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback

cannot pass learnyounode: is the callback function used uncorrectly?

I am trying to solve the sixth problem of learnyounode which needs a module file to print file list. Here are my two files:
The main file program.js:
var mymodule = require('./module.js');
mymodule(process.argv[2], process.argv[3], function(err, file){
if(err){
console.log(err);
return;
}
console.log(file);
});
The module file module.js:
var fs = require('fs');
var path = require('path');
var fileExt;
module.exports = function(dir, ext, callback) {
fs.readdir(dir, function(err, files){
if(err){
callback(err);
return;
}
files.forEach(function(file){
fileExt = path.extname(file).substring(1);
if(fileExt === ext){
callback(null, file);
}
});
});
}
But it throws an error:
processors[i].call(self, mode, function (err, pass) {
TypeError: Cannot read property 'call' of undefined
What am I doing wrong?
The instructions state that you need to call callback only once, with an array containing of all the matching files. In your case, you are calling callback once for every matching file.

Why is this readFile operation in Node throwing an error?

I have this code using socket.io on a Node server:
io.sockets.on(
'connection'
,function (socket) {
reader = require('fs');
fileContents = reader.readFile(__dirname + '/textCharacters.txt'
,'utf8'
,function(data, err) {
if (err) throw err;
console.log(data);
}
);
socket.emit('retrievedFileContent', {content:fileContents} );
}
);
When I check the Node server debug, the error shows the contents of the file, so I know the file is being read, but why isn't it being returned to the fileContents variable?
Because the readFile(filename, encoding, callback) function doesn't return the file contents, it passes them as the second argument to the given callback function. Try modifying your code as such:
var fs = require('fs');
io.sockets.on('connection', function (socket) {
var filename = __dirname + '/textCharacters.txt';
fs.readFile(filename, 'utf8', function(err, data) {
if (err) throw err;
socket.emit('retrievedFileContent', {content:data});
});
});

Resources