使用node.js保存json文件(Use node.js to save json file)

编程入门 行业动态 更新时间:2024-10-26 05:32:34
使用node.js保存json文件(Use node.js to save json file)

我对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.

更多推荐

本文发布于:2023-04-27 13:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1327128.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   js   node   json   file

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!