0

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

2 Answers 2

1

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!');
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.