JavaScript reads the file content in the folder, input file content to the console, web editor, showDirectoryPicker, entries, getFile, FileReader, readAsText

Article Directory


foreword

1. In this case, only the first-level directory is implemented, and the tree directory is not implemented. Competent friends can implement a web page editor based on this case, and can refer to Visual Studio Codethe web page editor for implementation.
2. fileArrayThere is a problem with the variable. If the custom variable receives the file handle, the tree directory function will not be realized. The specific reason has not been found yet, but you can check this article to solve the problem. The article has already implemented the tree directory structure normally, and the solution is found in the article JavaScriptpart .handle.children = [];

folderHandle


html

<div class="p_20 bs_bb">
	<div class="d_f jc_c">
		<button id="idFolder" class="w_50_ fs_30 cursor_pointer">打开文件夹</button>
	</div>
	
	<div id="idContent" class="m_t_20 bs_bb p_20 bc_rgba_192_1"></div>
</div>

JavaScript

global variable

let fileArray = [];

Used tofileArray save the obtained file handle.


Get file handles in folders

idFolder.onclick = async function () {
    
    
	try {
    
    
		let handle = await showDirectoryPicker();
		
		fileArray = await processHandle(handle);
		
		createDocment(fileArray);
	} catch (error) {
    
    
		console.log(error);
		// 用户拒绝的处理
	}
};

Use recursion to get a handle (handle handle)

async function processHandle(handle) {
    
    
	if (handle.kind === 'file') return handle;
	
	// 得到异步迭代器
	let iter = handle.entries(),
		fileArray = [];
	
	for await (let item of iter) fileArray.push(await processHandle(item[1]));
	
	return fileArray;
}

Create a first-level directory

function createDocment(fileList) {
    
    
	let innerHtmlStr = '';
	
	fileList.forEach(item => {
    
    
		if (item.name) innerHtmlStr += `<div class="p_6 bs_bb fs_18 w_fc cursor_pointer" οnclick="handleFileContent(event)">${
      
      item.name}</div>`;
	});
	
	idContent.innerHTML = innerHtmlStr;
}

Click on the file name to get the file content

function handleFileContent({
     
      target: {
     
      innerText } }) {
    
    
	fileArray.forEach(item => {
    
    
		if (item.name === innerText) readText(item);
	});
}

Read the contents of the file and output

async function readText(fileHandle) {
    
    
	let file = await fileHandle.getFile(),
		reader = new FileReader();
	
	reader.onload = ({
     
      target: {
     
      result } }) => {
    
    
		console.log(`-------输出结果-------\n${
      
      result}`);
	}
	
	reader.readAsText(file, 'utf-8');
}

Guess you like

Origin blog.csdn.net/weixin_51157081/article/details/132331768