使用文件系统包读取文件 [英] read a file using the file-system package

查看:103
本文介绍了使用文件系统包读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用文件系统软件包读取文件.

I am trying to read a file using the file-system package.

参考: https://www.npmjs.com/package/file-system

我要读取的文件与执行读取的文件位于同一目录中(如下图所示).

The file I am trying to read resides in the same directory as the file executing the read (visual below).

reduce2.js文件中的代码就是这样:

The code in the reduce2.js file is exactly this:

const fs = require('fs')

var output = fs.readFileSync('data.txt')

console.log(output);

这是我从命令行运行文件时遇到的错误:

This is the error I am getting when I run the file from the command line:

➜  js-practice node functional-programming-mpj/file-system-and-reduce/reduce2.js 
fs.js:638
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^

Error: ENOENT: no such file or directory, open 'data.txt'
    at Object.fs.openSync (fs.js:638:18)
    at Object.fs.readFileSync (fs.js:540:33)
    at Object.<anonymous> (/Users/jackburum/tutorials/js-practice/functional-programming-mpj/file-system-and-reduce/reduce2.js:3:17)
    at Module._compi

这告诉我文件系统模块找不到文件,但我不知道为什么.

which tells me that the file system module can't find the file, but I can't figure out why.

我尝试过的其他一些事情: -我也尝试使用导入而不是要求 -我尝试显式声明当前目录,例如

Some other things I have tried: - I tried using import as well instead of require - I tried explicitly declaring the current directory, like this

fs.readFileSync('./data.txt').

您知道我做错了什么,或者对我可以做些什么有任何想法吗?

Do you know what I am doing wrong or have any thoughts on what I could try to make this work?

推荐答案

问题是,您正在从另一个目录js-practice/执行node命令.

The problem is, you're executing node command from another directory: js-practice/.

要使fs.readFileSync('./data.txt');能够正常工作,您需要直接在file-system-and-reduce目录

For fs.readFileSync('./data.txt'); to work in your case you need to run node directly on file-system-and-reduce dir

file-system-and-reduce $ node reduce2.js

否则,节点尝试搜索:js-practice/data.txt在您的情况下不存在.

Otherwise node tries to search: js-practice/data.txt which doesn't exist in your case.

一个好的解决方案是使用: __dirname ,以及path.join,以便获取文件的绝对路径,这将使您可以从任何位置调用脚本.

A good solution is to use: __dirname, along with path.join, in order to get the absolute path to the file, which will allow you to call the script from any location.

const fs = require('fs'); // Native fs module
const path = require('path');

const output = fs.readFileSync(path.join(__dirname, 'data.txt'));

console.log(output);

请记住,您提供的参考不是本机文件系统模块.

Have in mind that the reference you provided, is not the native file system module.

  • Native: https://nodejs.org/docs/latest/api/fs.html (I recommend this)
  • 3rd party: https://www.npmjs.com/package/file-system

这篇关于使用文件系统包读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆