我有
import fs from 'fs'
在我的 package.json 中我有
然后我运行命令
> npm i fs
> [email protected] 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
},
.
.
.
.
})
这可能是环境问题。浏览器无法解释和运行某些 Node 服务器端模块,例如
fs
。
解决方案是在 Node 环境(服务器端)中运行
fs
方法,或者找到一个提供相同功能但为浏览器编写的包。
这个问题讨论过... 找不到模块:错误:无法解析模块“fs”
还有这个问题... 在 React.js、node.js、webpack、babel、express 中使用 fs 模块
这里出现了 fs 问题,必须下载 docx 格式的文件。原因是它是一个节点包没有反应,为了解决这个问题,我切换到文件保护程序包,它可以很好地满足我的要求,将 toBuffer 替换为 toBlob,将 fs 替换为 saveAs,示例代码如下。
//with fs
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer);
});
//with file saver
Packer.toBlob(doc).then(blob => {
console.log(blob)
saveAs(blob, 'MyDocument.docx')
})
您可以在这里了解有关文件保存程序的更多信息。 https://www.npmjs.com/package/file-saver
您可以使用包universal-fs,它允许您在客户端使用核心 Node:fs 功能。
完全披露我是这个包的创建者。
npm i babel-plugin-preval
虽然浏览器不允许在运行时访问文件系统,但您可以在React中使用prevail在构建时将文件系统中的内容读取到内存中 像这样
// loading content of text file into react project during build time.
// which means everytime text content is changed, you need to rebuild the project to get the updated content.
const greetingContent = preval`
const fs = require('fs')
module.exports = fs.readFileSync(require.resolve('./greeting.txt'), 'utf8')
`
console.log(greetingContent);