Introduction to Keytar
Keytar is a powerful Node.js module used for keychain access, which helps in securely storing and retrieving your application credentials. With Keytar, you can seamlessly manage your passwords and other sensitive information.
Keytar APIs
Let’s dive into dozens of useful APIs offered by Keytar along with code snippets to explain their usage.
Install Keytar
npm install keytar
Set a Password
const keytar = require('keytar');
keytar.setPassword('service', 'account', 'password')
.then(() => console.log('Password set successfully!'))
.catch(err => console.error('Failed to set password:', err));
Get a Password
const keytar = require('keytar');
keytar.getPassword('service', 'account')
.then(password => console.log('Password retrieved:', password))
.catch(err => console.error('Failed to get password:', err));
Delete a Password
const keytar = require('keytar');
keytar.deletePassword('service', 'account')
.then(result => console.log('Password deleted:', result))
.catch(err => console.error('Failed to delete password:', err));
Find Credentials
const keytar = require('keytar');
keytar.findCredentials('service')
.then(credentials => console.log('Found credentials:', credentials))
.catch(err => console.error('Failed to find credentials:', err));
Keytar App Example
Now, let’s create a simple application that uses the Keytar module to store and retrieve user credentials.
App Example
const keytar = require('keytar');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter service name: ', service => {
rl.question('Enter account name: ', account => {
rl.question('Enter password: ', password => {
keytar.setPassword(service, account, password)
.then(() => {
console.log('Password stored successfully!');
return keytar.getPassword(service, account);
})
.then(retrievedPassword => {
console.log('Retrieved password:', retrievedPassword);
return keytar.deletePassword(service, account);
})
.then(deleted => {
console.log('Password deleted:', deleted);
rl.close();
})
.catch(err => {
console.error('An error occurred:', err);
rl.close();
});
});
});
});
With these features, Keytar provides a straightforward way to handle sensitive data in your applications. Secure your app today with Keytar!
Hash: ca7f357f842c49aeae75282d1117181496704e4b2009d69b1a6faf4f6078acca