// plus.io API 封装的文件读写方法

/**
 * 写入 JSON 到文件
 * @param {string} fileName 文件名称(如 '_downloads/device.json' 或 plus.io.PRIVATE_DOC + '/device.json')
 * @param {Object} data 要写入的对象
 * @returns {Promise<boolean>} 是否写入成功
 */
function writeJsonToFile(fileName, data) {
	const filePath = `_downloads/${fileName}.json`
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL(filePath, function(entry) {
			entry.createWriter(function(writer) {
				writer.onwrite = function() {
					console.error('写入成功', fileName);
					resolve(true);
				};
				writer.onerror = function(e) {
					console.error('写入失败', e);
					reject(false);
				};
				writer.write(JSON.stringify(data));
			}, function(e) {
				console.error('创建写入器失败', e);
				reject(false);
			});
		}, function(e) {
			// 文件不存在则创建
			plus.io.resolveLocalFileSystemURL(filePath.substring(0, filePath.lastIndexOf('/')),
				function(dirEntry) {
					dirEntry.getFile(filePath.substring(filePath.lastIndexOf('/') + 1), {
						create: true
					}, function(fileEntry) {
						fileEntry.createWriter(function(writer) {
							writer.onwrite = function() {
								resolve(true);
							};
							writer.onerror = function(e) {
								console.error('写入失败', e);
								reject(false);
							};
							writer.write(JSON.stringify(data));
						}, function(e) {
							console.error('创建写入器失败', e);
							reject(false);
						});
					}, function(e) {
						console.error('创建文件失败', e);
						reject(false);
					});
				},
				function(e) {
					console.error('目录不存在', e);
					reject(false);
				});
		});
	});
}

/**
 * 读取 JSON 文件内容
 * @param {string} filePath 文件路径(如 '_downloads/device.json' 或 plus.io.PRIVATE_DOC + '/device.json')
 * @returns {Promise<Object|null>} 读取到的对象,失败返回 null
 */
function readJsonByFile(fileName) {
	const filePath = `_downloads/${fileName}.json`
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL(filePath, function(entry) {
			entry.file(function(file) {
				var reader = new plus.io.FileReader();
				reader.onloadend = function(evt) {
					try {
						resolve(JSON.parse(evt.target.result));
					} catch (e) {
						console.error('JSON解析失败', e);
						resolve(null);
					}
				};
				reader.onerror = function(e) {
					console.error('读取失败', e);
					resolve(null);
				};
				reader.readAsText(file, 'utf-8');
			}, function(e) {
				console.error('获取文件失败', e);
				resolve(null);
			});
		}, function(e) {
			console.error('文件不存在', fileName, e);
			resolve(null);
		});
	});
}

export default {
	writeJsonToFile,
	readJsonByFile
};

用法示例:
写入:

 import storage from '@/utils/storage.js'
 await storage.writeJsonToFile('companyInfo', {a:1})

读取:

 let obj = await storage.readJsonByFile('companyInfo')
    if (obj) {
      console.log('读取到内容:', obj);
    } else {
      console.log('读取失败或内容为空');
   }
 });
Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐