我正在尝试制作一个电子应用程序。
我想读取 json 文件 ( config, messages
( 并将它们保存到它们受人尊敬的地方。
问题是脚本会将第一个值的 json 保存在具有该名称的文件中。
脚本获取第一个值 json 并保存它,但随后没有获取下一个值来获取 json,只是将链接保存为文件格式。
var allText
var adminconfigjson
var adminconfigsave
var adminmessagesjson
var adminmessagessave
var adminconfigjson = "./assets/json/adminconfig.json"
var adminconfigsave = "./bot/AdminOptions/Config.json"
var adminmessagesjson = "./assets/json/adminmessages.json"
var adminmessagessave = "./bot/AdminOptions/Messages.json"
function create_bot() {
var json = [adminconfigjson, adminmessagesjson]
var newjson = [adminconfig, adminmessages]
var save = [adminconfigsave, adminmessagessave]
var text = ""
var i
for (i = 0; i < json.length; i++) {
console.log(json[i])
readTextFile(json[i])
function readTextFile(file) {
var rawFile = new XMLHttpRequest()
rawFile.open("GET", file, false)
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
for (i = 0; i < newjson.length; i++) {
newjson[i] = rawFile.responseText
console.log(newjson[i])
if (newjson[i] != "") {
for (i = 0; i < save.length; i++) {
var newsave = JSON.stringify(save)
for (i = 0; i < newjson.length; i++) {
if (newsave[i] != "") {
savefile(newsave[i], newjson[i])
console.log(save[i])
}
}
}
}
}
}
}
}
rawFile.send(null)
}
function savefile(filepath, content) {
fs.writeFile(filepath, content, function(err) {
console.log("file path" + filepath)
if (err) {
alert("An error ocurred updating the file" + err.message)
console.log(err)
return
}
alert("The file has been succesfully saved")
})
}
}
}
尽管代码和问题可以更好地表达,但您的目的是从源读取并将该 JSON 保存到新文件名下的目标。
我在没有引入 async/await 的情况下保留了它,因此您可以遵循最初提供的相同逻辑。
xhr
请求的问题在于,由于应用程序是electron
应用程序,因此您无需提取,因为文件基于本地应用程序。
如果您希望获取外部 JSON 文件,例如api
或外部FS
,那么您将需要为此包含一个 xhr 模块/调用。
const fs = require('fs')
const files = [{
source: "./assets/json/adminconfig.json",
destination: "./bot/AdminOptions/Config.json"
}, {
source: "./assets/json/adminmessages.json"
destination: "./bot/AdminOptions/Messages.json"
}]
// bot reads a config
// and then saves the content of source to destination
const create_bot = () => {
// note: you could make a symbolic link
// between the data directory and the output
// but that's up to you
//
// e.g.
// const filenames = fs.readdir(data_directory).then((error, filenames) => filenames)
// we iterate through each file_object
const filenames = files.forEach(file_object => {
// read the source
fs.readFile(file_object.source, "utf-8")
.then((err, content) => {
if (err) {
console.error(`An error ocurred reading the file: ${err.message}`)
throw new Error(err);
return
}
// write the file
// (destination, content, encoding) => callback
fs.writeFile(file_object.destination, content, "utf-8")
.then((err) => {
if (err) {
console.error(`An error ocurred updating the file: ${err.message}`)
throw new Error(err);
return
}
console.log("success")
}
})
})
}
create_bot();