I am using protractor cucumber framework.I need to write some data into a file and read that data also.But it is not working as expected.The code i have tried is given below.
const fs = require('fs');
After(function(){
var content = ["kerala","asam"];
var str=content.toString();
var content1 = ["india","usa","uk"];
var str1=content1.toString();
if(str){
fs.writeFile('test.txt', str, (err) => {
if (err) {
console.error(err);
return
}
});
}
if(str1){
fs.writeFile('test.txt', str1, (err) => {
if (err) {
console.error(err);
return
}
});
}
});
AfterAll(function(callback){
console.log("afterall");
fs.readFile('test.txt', 'utf-8', function(err, buf) {
console.log(buf.toString());
});
callback();
});
some time the arrays may be empty(depending on the test execution).so if the array having data, i need to write that data into a file and read also.But the after writing into the file the, the file having data as given below
india,usa,uk
it should be
kerala,asam
india,usa,uk
How can i do this .Thanks in advance.
Related
I am using NodeJs and MongoDb as a back-end service.In my collection i have several documents having fields named _id and Name but Node is returning only first document and showing error in console.I want to fetch only Name field of a document.
Error:
Here is my code:
var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.post('/offers',(req, res) => {
MongoClient.connect(url, (err, db) => {
if(err) throw err;
var dbo = db.db('Tiffino_db');
dbo.collection("Offers")
.find({},{ projection: { _id: 0 } })
.toArray((err, result) => {
if (err) {
console.log("Error:", +err);
}
else {
for(var i = 0;i<result.length;i++){
res.send(result[i].Name);
}
db.close();
}
});
});
});
Please let me know what I did wrong in above code.
THANKS
It looks like you're trying to send multiple responses in a loop using Response.Send() as a response is only sent once.
This won't work, you'll need to create an array of names, and then use Response.Send() to do this once.
Using res.send(result.map(r => r.name)) would probably work
You should aggregate the results into a variable and then call res.send() only once:
let resultString;
for(var i = 0;i<result.length;i++){
resultString += result[i].Name + '\n';
}
res.send(resultString);
If you want to stream the results, you can use res.write() and when done call res.end()
You can not use res.send() multiple time in a for loop, try somthing like this
var data=[];
for(var i = 0;i<result.length;i++){
data.push(result[i].Name);
}
res.send(data);
app.post('/offers',(req, res) => {
MongoClient.connect(url, (err, db) => {
if(err) throw err;
var dbo = db.db('Tiffino_db');
dbo.collection("Offers")
.find({},{ projection: { _id: 0 } })
.toArray((err, results) => {
if (err) {
console.log("Error:", +err);
}
else {
response = results.map(result => result.Name);
//res.send(response);
// in json format
res.json(response);
db.close();
}
});
});
});
...
...
else {
output = result.map(offer => offer.name);
res.send({output});
db.close();
}
This should work as you can only send response once on a single response object and you are calling that for results.length times.
I'm pretty sure you're not supposed to be calling res.send(...) multiple times. Since you're calling it inside a loop, it will send the first document and fail in the next as expected.
I am writing in Node.js.
And the in console I see the file names, and after that many strings: "File written", and in file I see one string with first filename in folder
Q: How do I write to TXT file an array with filenames from folder in Javascript?
Here is my code:
const WebmUrl = new URL('file:///D:/MY PROJCT/webm/hlp.txt');
fs.readdirSync(testFolder).forEach(file => {
console.log(file)
fs.writeFile(WebmUrl, file, function(err){
if(err) {
console.log(err)
} else {
console.log('File written!');
}
});
})
When you use fs.writeFile you replace the file if it exists. So in your loop you are continuously making a one item file and then replacing it on the next iteration.
You can use fs.appendFileSync or fs.appendFile
For example:
const fs = require('fs')
fs.readdirSync(directory).forEach(file => {
fs.appendFileSync(filename, file, function(err){
})
})
You could also just make an array of filenames, join them into a string and write all at once.
const fs = require('fs')
let str = fs.readdirSync(directory).join('\n')
fs.writeFile(filename, str, function(err){
if(err) {
console.log(err)
} else {
console.log('File written!');
}
});
Or you can add the append flag {flag: 'as'} see https://nodejs.org/api/fs.html#fs_file_system_flags
fs.readdirSync('../checkouts').forEach(file => {
console.log(file)
fs.writeFile('./test.txt', `${file}\n` , {flag: 'as'}, function (err) {
if (err) { console.log(err) }
else { console.log('File written!'); }
});
})
I am trying to get get the folder path from user's selection and for each file I read it and return the data. However upon getting the file I cannot read the data for some reason that I have't been able to understand yet. The directory I am trying to read and render do exist. I have referred to the other similar posts as well.
readFolder() {
dialog.showOpenDialog({ properties: ['openDirectory'] }, (dirFiles) => {
console.log(dirFiles);
if (dirFiles === undefined) {
console.log('No file ');
return;
}
const pathName = dirFiles[0];
fs.readdir(pathName, (err, files) => {
files.forEach(file => {
fs.readFile(file, 'utf-8', (err, data) => {
if (err) {
console.log(`something went wrong ${err}`);
} else {
console.log(data);
}
});
});
});
});
}
readdir returns filenames "a", "b", "c" etc. You want pathName + '/' + file for "/path/to/file/a"
The mistake I made was the fact that I hadn't realised the return values of 'file' which are just the names of the files as strings but not paths. Assinging let filePath =${pathName}/${file}; and reading it onwards solved the problem.
What i'm trying to do is read/write to multiple files at once, Once a file is created, only the data inside the file would be changed.
code:
var files = fs.readdirSync(__dirname+"/")
function readWrite(files) {
fs.readFile(files[i], 'utf-8', function(err, data){
if (err){
console.log(err)
}
fs.writeFile(files[i], 'test string', 'utf-8', function (err) {
if (err){
console.log("completed")
}
})
})
}
for(i in files){
readWrite(files[i])
}
The error is pretty obvious "path must be a string", But how do I go about writing to multiple files in the same directory at once?
I'm pretty new to node, so sorry if this seems like a bonehead question, any help would be appreciated.
You're passing filename to readWrite function so you should not use [i]:
function readWrite(file) {
fs.readFile(file, 'utf-8', function(err, data) {
if (err) {
console.log(err)
}
fs.writeFile(file, 'test string', 'utf-8', function (err) {
if (err) {
console.log("completed")
}
})
})
}
for (i in files) {
readWrite(files[i])
}
Try replacing files[i] by files inside your function. You should be using the name of your variable, files (and probably rename it to filepath)
After that, do you really want to read and write from the same file at the same time (this is what your code is doing) ?
I am trying to write the results of a MongoDB query to a file using the native Node.js driver. My code is the following (based on this post: Writing files in Node.js):
var query = require('./queries.js');
var fs = require('fs');
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/test", function(err, db) {
if(err) { return console.dir(err); }
var buildsColl = db.collection('blah');
collection.aggregate(query.test, function(err, result) {
var JSONResult = JSON.stringify(result);
//console.log(JSONResult);
fs.writeFile("test.json", JSONResult, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
});
collection.aggregate(query.next, function(err, result) {
var JSONResult = JSON.stringify(result);
//console.log(JSONResult);
db.close();
});
});
The file is written, but the contents are 'undefined.' Printing the result to the console works though.
Your code is not checking the err on the aggregate callback.
You are likely getting an Mongo error and the result is undefined in that case...
Other thing I could suspect is that you are getting multiple callbacks -- each one of them creates a new files, erasing the content.
Try using fs.appendFile instead of fs.writeFile and see if you are getting the expected data (plus the unwanted undefined)
For anyone stumbling across this the solution on where to put the db.close() is below:
collection.aggregate(query.test, function(err, result) {
var JSONResult = JSON.stringify(result);
//console.log(JSONResult);
fs.writeFile("test.json", JSONResult, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
collection.aggregate(query.next, function(err, result) {
var JSONResult = JSON.stringify(result);
//console.log(JSONResult);
db.close();
});
});