_fs.readFileSync is not a function

background

The project needs to read a local xlsx configurable file and generate a json format file.

I searched for information and found that the js xlsxlibrary can read and write xlsx files and convert formats. I also saw several blog posts about xlsx combined with elementui to process files, so I wrote the following code, and the result was an error: _fs.readFileSync is not a function

import xlsx from "xlsx"

const parseExcel = () => {
    
    
	const workBook = xlsx.readFile("template.xlsx",{
    
    });
	console.log(workBook);
}

reason

In a browser environment, due to security concerns, front-end JavaScript code cannot directly read local files, even accessing the file system on the local computer. This is because the browser's security mechanism restricts cross-domain access and access to local files, thereby preventing malicious scripts from obtaining users' sensitive data or modifying the local file system.

However, under certain circumstances, the function of reading local files at the front end can be realized through certain technical means. For example, the File API in the HTML5 standard can be used to allow the user to select a local file through the file selection box, and pass its content to the JavaScript code for processing. In addition, some development frameworks such as WebView and Electron can also be used to meet the needs of the front end to read local files through specific settings.

In other words, although xlsxthere are two functions for reading files, not all of these two functions can be used on the client side.

  • xlsx.read(data,read_opts)This function can be called on the client side, and can be used in conjunction with some file uploading components. The file data can be obtained through these file uploading components, and the file data can be parsed at the datafront end as it is passed in.
  • xlsx.readFile(Filename,read_opts)This function can only be used in nodejs, similar to fs, it cannot be used directly on the client side.

insert image description here
(The picture comes from: js-xlsx uses summary to realize front-end parsing excel , and xlsxsome detailed parameters of the library can also refer to this article)

Solution

  1. Get the file data by uploading the file at the front end, and use xlsx.read(data,read_opts)to get the file data.
  2. xlsx.readFile(Filename,read_opts)Read file in nodejs with function. this way to
import xlsx from "xlsx";

changed to

const xlsx = require("xlsx");

The way I use nodejs, the specific steps are recorded in: nodejs processes xlsx files to generate json files

Guess you like

Origin blog.csdn.net/Charonmomo/article/details/130697951