Advertisement
AMONUWNA

s

Jun 5th, 2022
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. import { Input, Output } from 'web-ext-native-msg';
  2. import { homedir } from 'os';
  3. import * as process from 'process';
  4. import * as patch from 'path';
  5. import * as fs from 'fs/promises';
  6.  
  7. const handleReject = e => {
  8. e = (new Output()).encode(e);
  9. e && process.stdout.write(e);
  10.  
  11. console.log(`there was an error: ${e}`);
  12. return false;
  13. };
  14.  
  15. const writeStdout = async msg => {
  16. msg = await (new Output()).encode(msg);
  17. return msg && process.stdout.write(msg);
  18. };
  19.  
  20. const handleMsg = async msg => {
  21. const dir = patch.resolve(homedir(), './.better-vulcan');
  22. const file = patch.resolve(dir, 'data.json');
  23. console.log(`read message: ${msg.type}`);
  24.  
  25. try {
  26. console.log(`creating new directory: ${dir}`);
  27. await fs.mkdir(dir);
  28. }
  29. catch {}
  30.  
  31. console.log(`saving message to: ${file}`);
  32. await fs.writeFile(file, JSON.stringify(msg));
  33.  
  34.  
  35. console.log(`message handled!`);
  36. writeStdout({ message: 'done!' });
  37. };
  38.  
  39. const input = new Input();
  40.  
  41. const readStdin = chunk => {
  42. const arr = input.decode(chunk);
  43. const func = [];
  44. Array.isArray(arr) && arr.length && arr.forEach(msg => {
  45. msg && func.push(handleMsg(msg));
  46. });
  47.  
  48. console.log(`read ${arr.length} messages`);
  49. return Promise.all(func).catch(handleReject);
  50. };
  51.  
  52.  
  53. console.log(`start!`);
  54. process.stdin.on('data', readStdin);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement