简体   繁体   中英

async read and output file using node.js

I want to collect all of my files name in a folder and output it to a json file. I have 2 problem, first one I don't know how to do callback. Then I'll skip that one, but I tried the settimeout example, I did not see any .json file also. I wonder that's wrong.

const imagesFolder = './assets/images';
const fs = require('fs');
const jsonfile = require('jsonfile');

let json = [];
fs.readdir(imagesFolder, (err, files) => {
  files.forEach(file => {
    json.push(file.split('.')[0])
  });
})

setTimeout(function(){
    var obj = {"foo":"bar"}
    jsonfile.writeFile(imagesFolder, obj);
},1000) 

You can do this synchronously in readdir callback. Also, I believe you need to pass a file name to jsonfile.writeFile :

fs.readdir(imagesFolder, (err, files) => {
  files.forEach(file => {
    json.push(file.split('.')[0]);
  });

  jsonfile.writeFile(`${imagesFolder}/files.json`, json);
});

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