简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM