Error : Path must be a string, NodeJS Read/Write - javascript

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

Related

How to write multiple strings into a file in protractor(js)

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.

How to write to TXT file an array with filenames from folder in Javascript

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

How can I use Node.js to check if a directory is empty?

I asked this question for PHP a long time ago. The same applies for Node.js the code below seems a little slow when using in a loop - is there a way for writing this in pure Node.js vanilla JavaScript without plugins or React.js etc?
const dirname = 'cdn-assets/'
fs.readdir(dirname, function(err, files) {
if (err) {
// some sort of error
} else {
if (!files.length) {
// directory appears to be empty
}
}
});
Also, can I write a further conditional to check:
if(directory_has_these_files('.js, .css, .jpg, .svg, .mp4'))
So if you do this
fs.readdir('/path/to/empty_dir', (data, err) => console.log(data, '.....', err))
You'll see that the result is:
null '.....' []
So your code can be simplified as
fs.readdir(dirname, (err, files) => {
if (err && !files) {
console.error(err)
}
console.info('the files --> ', files)
let regexp = RegExp('.jpeg|.doc|.png|.zip', 'gi')
for(result in files) {
if(regexp.test(files[result])) {
console.log('I have the following', files[result])
}
}});
However....
We want this quick, modern and efficient, don't we?!
So this is even better:
fs.readdir(dirname, (err, files) => {
if (err && !files) {
console.error(err)
}
let regexp = RegExp('.jpeg|.doc|.png|.zip', 'gi');
files.filter(
file => file.match(regexp)
).map(
result => console.log('I have the following',result)
);
});
One of the advantages to using a map on a directory, is that you'll guarantee the preservation of order, it also looks cleaner.
Map is built-in iterable — Object is not, this is not to say the Map is a replacement for Object, there are use cases for both. That's another story.

Error: ENOENT: no such file or directory

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.

delete all files in folder

how to delete files in project catalogue during yeoman process?
initializing() {
this.sourceRoot('./generators/templates');
this.destinationRoot('./generators/project');
console.log(this.destinationPath());
console.log(this.sourceRoot());
this.fs.delete(this.destinationPath());
this.fs.delete(this.destinationPath('**/*'));
this.fs.delete('project');
this.fs.delete('./generators/project');
this.fs.delete('generators/project');
this.fs.delete('generators/project/**/*');
}
non of these seems to work :(
fs.readdir('path here', (err, files) => {
if (err) console.log(err);
for (const file of files) {
fs.unlink(path.join('path here', file), err => {
if (err) console.log(err);
});
}
});
If you want to delete a file using fs you should use fs.unlink(path, callback) or fs.unlinkSync(path).
// Asynchronous version
fs.unlink('file.txt', function(err) {
if(!err) {
console.log('file deleted');
}
}
// Synchronous version, deprecated
fs.unlinkSync('file.txt');
Make sure you have the newest version of node installed to make sure this is available.

Categories

Resources