【问题标题】:React Js require 'fs'React Js 需要 'fs'
【发布时间】:2016-05-02 10:23:29
【问题描述】:

我有

import fs from 'fs'

在我的 package.json 中有

然后我运行命令

>  npm i fs
>  fs@0.0.2 node_modules/fs

接下来在我的 React 商店中导入“fs”模块

import fs from 'fs'

但是当我尝试使用 fs 时

除了构造函数和其他一些 __methods 之外,我没有看到其他方法。我没有看到 createReadStream 方法或任何其他文件操作方法。

有人知道怎么回事吗? (使用 Webpack)并且可以根据要求提供更多信息,但我已经走到了这一步......

ps:为什么我可以 npm i fs --save 阅读其他我不必这样做的帖子(使用节点 5.5.0)

import Reflux from 'reflux'
import AddItemActions from '../actions/AddItemActions'
import request from  'superagent-bluebird-promise'
import fs from 'fs'

var ImageStore = Reflux.createStore({
  init(){
    .
    .
    .
  },

  decryptImage(file) {
    var reader = new FileReader();
    var info = {}
    reader.onload = (output) => {
      debugger
      request.post("https://camfind.p.mashape.com/image_requests")
        .set("X-Mashape-Key", "KEY")
        .set("Content-Type", "application/x-www-form-urlencoded")
        .set("Accept", "application/json")
        .send({'focus': { 'x': 480}})
        .send({'focus': { 'y': 640}})
        .send({'image_request': {'altitude': 27.912109375}})
        .send({'image_request': {'language': "en"}})
        .send({'image_request': {'latitude': 35.8714220766008}})
        .send({'image_request': {'locale' : "en_US"}})
        .send({'image_request': {'longitude': 14.3583203002251}})
        .send({'image_request': {'image': fs.createReadStream("/path" + 'file.jpg')}})
        .then(function (result) {
          console.log(result.status, result.headers, result.body);
          this.info = result
        },
          function(error) {
            console.log(error);
        })
    }

    reader.readAsDataURL(file);
    return info
  },
  .
  .
  .
  .
})

【问题讨论】:

  • stackoverflow.com/questions/24594796/… 的可能欺骗。 fs 是节点核心模块的一部分。
  • 您希望在这里发生什么? fs 是一个与文件系统一起工作的节点模块。它的大多数方法在浏览器中都不起作用。
  • 哦,我明白了......我想我可以在我的 react 应用程序中包含任何节点包......那么有 Javascript 的等价物吗?
  • 浏览器不允许访问文件系统。你想达到什么目的?
  • 函数decryptImage。有一个参数 image_request[image] 接受文件流。我想通过我的反应发送它是应用程序

标签: reactjs webpack fs mashape


【解决方案1】:

这可能是环境问题。浏览器无法解释和运行某些 Node 服务器端模块,例如 fs

解决方案是在 Node 环境(服务器端)中运行 fs 方法,或者找到一个提供相同功能但为浏览器编写的包。

在这个问题中讨论过...... Module not found: Error: Cannot resolve module 'fs'

而这个问题... Use fs module in React.js,node.js, webpack, babel,express

【讨论】:

【解决方案2】:

create-react-app 中,他们删除了“fs”。你不能导入它。 他们这样做是因为fs 是一个节点核心模块。
您必须找到解决该问题的另一种方法。见this ticket.

【讨论】:

    【解决方案3】:

    npm i babel-plugin-preval

    如果你想在 React 中使用 Node 的 fs,你可以在 React 中使用 prevail 像这样

    const greetingContent = preval`
      const fs = require('fs')
      module.exports = fs.readFileSync(require.resolve('./greeting.txt'), 'utf8')
    `
    console.log(greetingContent);
    

    【讨论】:

      猜你喜欢
      • 2016-09-29
      • 2013-07-09
      • 2022-11-27
      • 2016-10-06
      • 2017-10-06
      • 2021-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多