)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Save a Text File with JavaScript

  1. function saveFile(text, name = 'file', mime = 'text/plain') {
  2.   const blob = new Blob([
  3.     text
  4.   ], { type: mime });
  5.   const a = document.createElement('a')
  6.  
  7.   a.download = name + '.txt'
  8.   a.href = window.URL.createObjectURL(blob)
  9.   a.click();
  10. }
  11.  
  12. // hacky way to create the button and have it call `saveFile`
  13. // when clicked
  14. document.body.appendChild(
  15.   Object.assign(
  16.     document.createElement`button`,
  17.   { innerText: 'click me' })
  18. ).onclick = () => saveFile('Hello there')

Write An Array of Files in Node

  1. const fs = require('fs');
  2.  
  3. function writeNextFile(file, content, files, done) {
  4.   fs.writeFile(file, content + '\n', () => {
  5.     const next = files.shift();
  6.     if (!next && done != null) {
  7.       done();
  8.       return;
  9.     }
  10.     writeNextFile(next.file, next.content, files, done);
  11.   });
  12. }
  13. function writeFiles(files, cb) {
  14.   const curr = files.shift();
  15.   writeNextFile(curr.file, curr.content, files, cb);
  16. }
  17.  
  18. writeFiles(
  19.   [
  20.     {
  21.       file: 'zevan1.txt',
  22.       content: 'hello world'
  23.     },
  24.     {
  25.       file: 'zevan2.txt',
  26.       content: 'goodbye world'
  27.     },
  28.     {
  29.       file: 'confusing.txt',
  30.       content: 'greetings world'
  31.     }
  32.   ],
  33.   () => {
  34.     console.log('done');
  35.   }
  36. );

Wrote this snippet for a friend a few weeks back… I don’t do tons of node, so maybe there is a better way but….

// io // javascript // node
snippet.zone ~ 2021-24 /// {s/z}