0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Electron でダイアログを開いてファイルを開く/保存

Last updated at Posted at 2019-07-27

Electron でダイアログを開いてファイルを開く/保存

pify を使用してPromise化した。

const fs = require('fs')
const pify = require('pify')
const { BrowserWindow, dialog } = require('electron').remote

/**
 * ダイアログで任意のファイルを開く
 * @param dialogOptions
 * @param fileOptions
 * @returns {Promise<undefined>}
 */
export const openFileDialog = async (dialogOptions, fileOptions = 'utf8') => {
  const win = BrowserWindow.getFocusedWindow()
  const fileNames = await pify(
    dialog.showOpenDialog(win, {
      ...dialogOptions,
      properties: ['openFile'],
    })
  )
  return fileNames ? readFile(fileNames[0], fileOptions) : undefined
}

/**
 * ダイアログで任意のファイル保存
 * TODO: openFileDialog と同様に pify を使用して Promise化して実行結果を返したい。
 * @param data
 * @param options
 */
export const saveFileDialog = (data, options = {}) => {
  const win = BrowserWindow.getFocusedWindow()
  dialog.showSaveDialog(win, options, fileName => {
    writeFile(fileName, data)
  })
}

/**
 * 指定したファイルを読み込む
 * @param path
 * @param option
 * @returns {Buffer}
 */
export const readFile = (path, option) => {
  return fs.readFileSync(path, option)
}

/**
 * fileを保存(Pathと内容を指定)
 * @param path
 * @param data
 */
export const writeFile = (path, data) => {
  return fs.writeFileSync(path, data)
}
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?