我对Node服务器/ javacsript很新。 所以我很抱歉,如果这可能是愚蠢的问题/主题。
我打算创建一个非常简单的解决方案来打开JSON文件,加载列表并将其保存回本地磁盘(运行node.js服务器)。
你能帮我解决,我做错了什么? 我使用反应在浏览器中运行应用程序。
包含index.js
var fs = require('fs'); var fileName = './test.json'; var file = require('./test.json'); alert(file.name + " " + file.age); file.name = "Peter"; alert(file.name + " " + file.age); fs.writeFile('./test.json', JSON.stringify(file), function (err) { if (err) return alert(err); console.log(JSON.stringify(file)); alert('writing to ' + fileName); });在我甚至无法打开JSON文件之前。 我需要将此属性包含到webpack配置文件中。
node: { fs: 'empty' }现在我可以打开JSON文件,虚拟地改变它,但无法保存它。 在Chrome开发者工具中,它将“ fs.writeFile不是一个函数 ”打印到控制台中。
非常感谢你。
I am very new to Node server/javacsript. So I am sorry if this might be stupid question/topic.
I intended to create a very simple solution to open JSON file, load to list, and save it back to my local disk (running node.js server).
Could you please help me out, what I am doing wrong? I am running app in browser using react.
index.js containing
var fs = require('fs'); var fileName = './test.json'; var file = require('./test.json'); alert(file.name + " " + file.age); file.name = "Peter"; alert(file.name + " " + file.age); fs.writeFile('./test.json', JSON.stringify(file), function (err) { if (err) return alert(err); console.log(JSON.stringify(file)); alert('writing to ' + fileName); });Before I was not even able to open JSON file. I needed to include this property into the webpack config file.
node: { fs: 'empty' }Now I am able to open JSON file, change it virtually, but unable to save it. In chrome developer tools, it prints "fs.writeFile is not a function" into console.
Thank you very much.
最满意答案
当您将该属性包含在您的webpack配置中时
node: { fs: 'empty' }你告诉webpack,模块fs应该只是一个空对象。 你可以通过简单地在你的文件中放一个console.log(fs)来确认它,看看它确实是空的。
除此之外, fs不会在您的浏览器中工作。 fs期望node.js运行时(包含非JavaScript事物以使其工作),而不是浏览器的运行时。
如果您希望用户保存文件,则必须使用基于浏览器的保存解决方案。 除了浏览器的本地存储之外,您无法任意写这种文件。
When you included the property in your webpack config
node: { fs: 'empty' }You told webpack that the module fs should just be an empty object. You can confirm this by simply putting a console.log(fs) in your file to see it is indeed empty.
Beyond that, fs is not going to work in your browser. fs expects the node.js runtime (which includes non-JavaScript things in order to make it work), not your browser's runtime.
If you want a user to save a file, you'll have to use a browser based saving solution. You won't be able to just arbitrarily write files like that outside of something like your browser's local storage.
更多推荐
发布评论