SHARE
TWEET

NodeJS Read Write Files by Ngekoding

ngekoding May 31st, 2020 (edited) 800 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require('fs')
  2. const readline = require('readline');
  3.  
  4. function clear(filename) {
  5.   if (fs.existsSync(filename)) {
  6.     fs.writeFile(filename, '', (err) => {
  7.       if (err) throw err;
  8.     });
  9.   }
  10. }
  11.  
  12. function create(max) {
  13.   // (optional) Remove if you don't need
  14.   clear('data.txt');
  15.  
  16.   // Write the file
  17.   for (let i = 1; i <= max; i++) {
  18.     let br = i != max ? '\n' : '';
  19.     fs.appendFileSync('data.txt', i + br, (err) => {
  20.       if (err) throw err;
  21.     });
  22.   }
  23. }
  24.  
  25.  
  26. // Create the data
  27. create(100);
  28.  
  29. // Seperate the data into some files
  30. // e.g. Each file contains 20 line
  31. async function separate(num) {
  32.   const fileStream = fs.createReadStream('data.txt');
  33.   const rl = readline.createInterface({
  34.     input: fileStream,
  35.     crlfDelay: Infinity
  36.   });
  37.  
  38.   let numFile = 1;
  39.   let i = 1;
  40.  
  41.   // (optional) Remove if you don't need
  42.   clear(`data-${numFile}.txt`);
  43.  
  44.   for await (const line of rl) {
  45.     fs.appendFileSync(`data-${numFile}.txt`, line + '\n', (err) => {
  46.       if (err) throw err;
  47.     })
  48.  
  49.     // We need to increase the numFile (file name)
  50.     // for each {num} line
  51.     if (i % num == 0) {
  52.       numFile++;
  53.       // (optional) Remove if you don't need
  54.       clear(`data-${numFile}.txt`);
  55.     }
  56.    
  57.     // Increase current line number
  58.     i++;
  59.   }
  60. }
  61.  
  62. // Seperating the data
  63. separate(20);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top