node.js reading null string at the end of file - node.js

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

Related

how to add new line using fs.writeFile?

I tried to write my project's files to a new file, each one in new line, using Node.js. How can I do that? Below is my code:
var fs = require('fs');
var colors = require('colors');
fs.readdir('./', 'utf-8', function(err, data) {
if (err) throw err;
console.log(data);
fs.writeFile('./new.txt', data, function(err) {
if (err) throw err;
console.log('Saved!'.blue);
});
});
You can collect all filenames first and then write them to a file.
const fs = require('fs');
const colors = require('colors');
let fileNames = '';
fs.readdir('./', 'utf-8', function(err, data) {
data.forEach(filename => fileNames += filename + '\n');
fs.writeFile('./new.txt', fileNames, function(err) {
if (err) throw err;
console.log('Saved!'.blue);
});
});

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 );

process out of memory on big file load to mongo in node

I'm trying to save and parse large .csv files and save the data in MongoDB, keeping the results in string type. So I'm trying to pipe the .csv file data, through a parser and then write the data to MongoDB.
I tried parsing the .csv to a json file and using mongoimport to upload it to MongoDB, which worked fine, but the values weren't kept as strings and you cant set values when using mongoimport.
I also don't want to set the memory for node and try and use as little memory as possible.
My problem at the moment is: the program runs out of memory and throws:
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory
var fs = require('fs');
var parse = require('csv-parse');
var async = require('async');
var queue, stream;
var headers = fileData.subText.meta.fields;
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var collection = db.collection(fileData.collectionName);
var parser = parse({columns: fileData.subText.meta.fields, delimiter: fileData.delimiter});
stream = fs.createReadStream("filepath" + fileData.name).pipe(parser);
var data;
queue = async.queue(function (task, next) {
data = task.data;
collection.insert(data, function (err, result) {
if (err) {
db.close();
console.log(err);
} else {
next();
}
});
}, 50);
stream.on('data', function (data) {
stream.pause();
queue.push({
data: data
});
});
queue.drain = function () {
stream.resume();
};
stream.on('end', function () {
return queue.drain = function () {
db.close();
return console.log('Process Done');
};
});
});
I got the idea from this link: https://bassnutz.wordpress.com/2012/09/09/processing-large-files-with-nodejs/
Any help would be appreciated.

Reading a .txt file with NodeJS using FS

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);
});

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