Creating a Tauri application with Vanilla JavaScript that allows users to select a folder, create, modify, and delete .txt files is a great project! Below is a step-by-step guide to help you build this application using Tauri with npm.
Prerequisites
Before we start, make sure you have the following installed:
- Node.js (v14 or higher)
- npm (v6 or higher)
- Rust and Cargo: While you mentioned not using Cargo directly, Tauri apps require Rust for the backend. You need to have Rust installed.
To install Rust, run:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
Step 1: Install the Tauri CLI
Although Tauri applications are built with Rust, you can use the Tauri CLI via npm. Install the Tauri CLI globally with:
npm install -g @tauri-apps/cli
Note: You might need to use sudo depending on your system permissions.
Step 2: Initialize a New Tauri Project
Create a new directory for your project and navigate into it:
mkdir tauri-notes-app
cd tauri-notes-app
Initialize a new Node.js project:
npm init -y
Install Tauri and required dependencies:
npm install @tauri-apps/cli @tauri-apps/api
Initialize a new Tauri project:
npx tauri init
During initialization, you will be prompted with some questions. You can accept the defaults or adjust according to your preference.
Step 3: Set Up the Frontend
Since you want a minimalistic frontend with Vanilla JavaScript, we'll set up a simple index.html file.
Create an index.html file in the src directory:
<!-- src/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tauri Notes App</title>
<style>
body {
margin: 0;
height: 100vh;
cursor: pointer;
}
</style>
</head>
<body>
<script src="index.js"></script>
</body>
</html>
Create an index.js file in the src directory:
// src/index.js
window.addEventListener('DOMContentLoaded', () => {
document.body.addEventListener('click', () => {
createNewNote();
});
});
async function createNewNote() {
// This function will handle creating a new note
}
Step 4: Prompt User to Select a Folder on First Launch
We need to prompt the user to select a folder upon the first launch. We'll use Tauri's dialog API for this.
Update index.js:
// src/index.js
const { dialog, fs } = window.__TAURI__.api;
let notesDirectory = null;
window.addEventListener('DOMContentLoaded', async () => {
// Check if notes directory is set in local storage
notesDirectory = localStorage.getItem('notesDirectory');
if (!notesDirectory) {
await promptForNotesDirectory();
}
document.body.addEventListener('click', async () => {
await createNewNote();
});
});
async function promptForNotesDirectory() {
const selected = await dialog.open({
directory: true,
multiple: false,
title: 'Select Notes Directory',
defaultPath: await fs.appDir(),
});
if (selected) {
notesDirectory = selected;
localStorage.setItem('notesDirectory', notesDirectory);
} else {
// Handle if user cancels the dialog
alert('Please select a directory to store notes.');
await promptForNotesDirectory();
}
}
Step 5: Create a New Note on Click
We will create a new .txt file in the selected directory when the user clicks anywhere on the page.
Update the createNewNote function:
async function createNewNote() {
const { fs, path } = window.__TAURI__.api;
// Generate a unique file name
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const fileName = `Note-${timestamp}.txt`;
const filePath = await path.join(notesDirectory, fileName);
// Create an empty file
await fs.writeFile({ path: filePath, contents: '' });
alert(`New note created: ${fileName}`);
}
Step 6: Implement File Modification and Deletion (Optional)
To modify and delete files, you can extend your application with additional UI elements.
Modifying Files
- List all files in the notes directory.
- Allow the user to select a file to open.
- Display the file contents in a text area for editing.
- Save changes back to the file.
Deleting Files
- Provide a list of files with a delete button next to each.
- Use
fs.removeFile to delete the selected file.
Step 7: Update Tauri Configurations
Ensure that Tauri is configured correctly to allow access to the filesystem.
Edit tauri.conf.json:
{
"tauri": {
"security": {
"csp": null
},
"allowlist": {
"all": false,
"fs": {
"all": true,
"scope": ["$DIR_ALL"]
},
"dialog": {
"all": true
},
"path": {
"all": true
}
}
}
}
This configuration allows access to the filesystem, dialogs, and path APIs. Adjust the scope in the fs configuration to restrict access as needed.
Step 8: Build and Run the Application
To run the application in development mode:
npm run tauri dev
This command should start the Tauri development server and open your application window.
Additional Notes
-
Security Considerations: Be cautious with filesystem access. Ensure that your application only accesses directories that the user has explicitly allowed.
-
Error Handling: Add proper error handling to your functions to handle exceptions gracefully.
-
Styling: Since the application is minimalistic, you might want to keep the style simple. However, feel free to customize the UI to enhance user experience.
Complete index.js File
For completeness, here's the full index.js code with added comments:
// src/index.js
const { dialog, fs, path } = window.__TAURI__.api;
let notesDirectory = null;
window.addEventListener('DOMContentLoaded', async () => {
notesDirectory = localStorage.getItem('notesDirectory');
if (!notesDirectory) {
await promptForNotesDirectory();
}
document.body.addEventListener('click', async () => {
await createNewNote();
});
});
async function promptForNotesDirectory() {
const selected = await dialog.open({
directory: true,
multiple: false,
title: 'Select Notes Directory',
defaultPath: await fs.appDir(),
});
if (selected) {
notesDirectory = selected;
localStorage.setItem('notesDirectory', notesDirectory);
} else {
alert('Please select a directory to store notes.');
await promptForNotesDirectory();
}
}
async function createNewNote() {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const fileName = `Note-${timestamp}.txt`;
const filePath = await path.join(notesDirectory, fileName);
// Create an empty file
try {
await fs.writeFile({ path: filePath, contents: '' });
alert(`New note created: ${fileName}`);
} catch (error) {
console.error('Failed to create note:', error);
alert('Failed to create note. Check console for details.');
}
}
Conclusion
You've now set up a basic Tauri application with Vanilla JavaScript that prompts the user to select a folder and allows them to create new .txt notes by clicking anywhere on the page. From here, you can expand the application to add features like viewing and editing notes, searching, and more.
References:
Feel free to ask if you have any questions or need further assistance!