Saving files locally with electron

2019-01-21 14:02发布

问题:

I have some template files that contain a few variable strings each, I'd like to build a very simple input form with Electron (http://electron.atom.io/) and I want to save the composed output file on the user's computer.

Is there any module I can use to let Electron save files locally?

回答1:

If you are targeting multiple platforms, I answered a similar question here. Basically app.getPath(name), app.setPath(name, path), and app.getAppPath() are very useful in saving files to the the right place regardless of the OS.

You may also want to check out these Nodejs packages which help simplify saving files directly to the host machine...

  • fs-jetpack
  • graceful-fs
  • Node.js fs

If you intend for users to save files you might also have a look at the Dialog api where you can specifically invoke a save dialog for that purpose.



回答2:

A sample code is :

// your content is into a variable named 'content'
var fs = require('fs');
try { fs.writeFileSync('myfile.txt', content, 'utf-8'); }
catch(e) { alert('Failed to save the file !'); }


回答3:

Electron's JavaScript is actually in Node.js, so you can learn about the File System API. Documentation of File System