javascriptelectronnode.js-fs

Convert file of consts to string and save it in fs


I'm newbie with electronjs so i tried to save my file as a TXT file via fs like this:

simple consts in data.ts file:

export const users = [{ id: 1, name: 'a', classId: 1 }]

export const classes = [
  { id: 1, name: 'A', booksId: [1, 2] },
]

export const books = [
  { id: 1, name: 'math' },
  { id: 2, name: 'physic' },
]

export const usersScore = [
  {
    userId: 1,
    scores: [
      { bookId: 1, score: 20 },
      { bookId: 2, score: 20 },
    ]
  }
]

After that I create an ipc in main.js to save file from App.tsx file

main.js file:

ipcMain.on('saveFile', (e, data) => {
  // Convert the data to a JSON string
  const jsonData = JSON.stringify(data, null, 2)

  dialog
    .showSaveDialog({
      title: 'Select the File Path to save',
      defaultPath: path.join(__dirname, '../assets/students.txt'),
      // defaultPath: path.join(__dirname, '../assets/'),
      buttonLabel: 'Save',
      // Restricting the user to only Text Files.
      filters: [
        {
          name: 'Text Files',
          extensions: ['txt', 'docx']
        }
      ],
      properties: []
    })
    .then((file) => {
      if (!file.canceled) {

        // Creating and Writing to the sample.txt file
        fs.writeFile(file.filePath.toString(), jsonData, (err) => {
          if (err) throw err
          console.log('Saved!')
        })
      }
    })
    .catch((err) => {
      console.log('err', err)
    })
})

and in my renderer file

App.tsx file:

import { Link } from 'react-router-dom'
import * as data from './utils/constants'
// import bridge from './utils/bridge'

function App(): JSX.Element {
  const save = () => {
    // send the data to main 
    window.electron.ipcRenderer.send('saveFile', data)
  }

  return (
    <>
      <button onClick={save}>save</button>
    </>
  )
}

export default App

but i got this error when i clicked on save button

enter image description here

I checked the type of jsonData and it says string!


Solution

  • The problem you are facing is in the way you are importing data. When you type import * as data from './utils/constants’, you are not importing just what you need but the whole module instead.

    Assuming you would like to send all the properties stored in the "constants file", first you have to store them in a JS plain object and then send them through send()

    Something like the following:

    import { users, classes, books, usersScore } from './utils/constants';
    
    function App(): JSX.Element {
      const save = () => {
        const dataToSend = { users, classes, books, usersScore };
        window.electron.ipcRenderer.send('saveFile', dataToSend);
      };
    
      return (
        <>
          <button onClick={save}>Save</button>
        </>
      );
    }
    
    export default App;