简体   繁体   English

JavaScript中如何读取本地文件内容

[英]How to read contents on a local file in JavaScript

I want to start off by saying that I do not think this is a duplicate because any other question I've found of this nature is based on getting the files contents from a document.getElement tag where the user is choosing a file and going from there.我想首先说我不认为这是重复的,因为我发现的任何其他这种性质的问题都是基于从 document.getElement 标签中获取文件内容,用户正在从中选择文件并从那里。 I'm trying to read in a file that is in a folder on my computer.我正在尝试读取计算机文件夹中的文件。 In my C drive.在我的 C 驱动器中。 I haven't been able to find anything along these lines and would appreciate any help or being pointed in the right direction.我一直没能找到任何沿着这些方向的东西,如果有任何帮助或被指出正确的方向,我将不胜感激。 I am trying to find out if this is possible or not using raw v8 js.我正在尝试使用原始 v8 js 来确定这是否可行。

It depends a lot on the context, and where the file is currently located.这在很大程度上取决于上下文以及文件当前所在的位置。

For a user-specified file, your only way of accessing that is asking the user to upload it via a <input type="file"> input element.对于用户指定的文件,您唯一的访问方式是要求用户通过<input type="file">输入元素上传它。

For a backend file (ie on your machine), in JS there are multiple different runtimes, all of which have different methods of importing or referencing local files.对于后端文件(即在您的机器上),在 JS 中有多个不同的运行时,所有这些运行时都有不同的导入或引用本地文件的方法。

You mention in a comment that you're using "raw" JS via the V8 engine, which doesn't have any capabilities for accessing local files.您在评论中提到您正在通过 V8 引擎使用“原始”JS,它没有任何访问本地文件的功能。

However, if you set up access to the Node.js ecosystem of libraries you can use the fs file-loading tool, like so:但是,如果您设置了对 Node.js 库生态系统的访问权限,则可以使用fs文件加载工具,如下所示:

fs.readFile('filepath', (err, data) => {
  if (err) throw err;
  console.log(data);
});

(docs here ) (文档在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM