我正在使用Node将.csv
文件预处理.json
为使用CSVTOJSON
npm包的文件。
我想等待解析完成,然后启动将上传过程上传到数据库。
我发现Node需要链接带有回调的函数才能异步执行它们。
但是我不知道如何应用到我的程序中。
这是代码。
// 1. Read *.csv file + Parse fields and escape; @dir "raw_data" => @dir "processed"
fs.readdir(rawDataPath, function (err, files) {
if (err) return console.log("Unable to scan raw_data : " + err);
console.log("Processing csv files to JSON...");
console.log("+++++++++++++++++++++++++++++++++++++++++++++++++++++++");
files.forEach(function (file) {
console.log(`CSV ${file.split(".")[0]} being converted...`);
csv({ ignoreEmpty: true })
.fromFile("raw_data/" + file)
.then((jsonObj) => {
// stringify JSON Object
var jsonContent = JSON.stringify(jsonObj);
fs.writeFile(
`processed_data/${file.split(".")[0]}.json`,
jsonContent,
"utf8",
function (err) {
if (err) {
console.log(
"An error occured while writing JSON Object to File."
);
return console.log(err);
}
console.log(
`${file} successfully converted to ${file.split(".")[0]}.json`
);
}
);
});
});
});
// 2. Upload to Cloud Firestore
fs.readdir(processedDataPath, function (err, files) {
if (err) return console.log("Unable to scan processed_data : " + err);
files.forEach(function (file) {
var quiz = require("./processed_data/" + file);
console.log(`Collection ${file.split(".")[0]} being updated...`);
quiz.forEach(function (obj) {
firestore
.collection(`${file.split(".")[0].toUpperCase()}`)
.doc(obj.id)
.set(obj)
.then(function (docRef) {
console.log(
`Document ${obj.id} successfully uploaded to Cloud Firestore!`
);
})
.catch(function (error) {
console.error("Error adding document: ", error);
});
});
});
});
有多种方法可以处理Javascript的异步特性。我将以fs.readFile()
一个简单的例子为例。这些是一些方法-
fs.readFile('./some-file.txt', (err, res) => {
if (err) { // err is null if success
return console.log(err); // handle error
}
console.log(res); // handle success
});
fs.promises.readFile('./some-file.txt').then((res) => {
console.log(res); // handle success
}).catch((err) => { // only gets executed if there is an error
console.log(err); // handle error
});
链接-
fs.promises.readFile('./some-1.txt').then((res) => {
return fs.promises.readFile('./some-2.txt');
// handle success - 1
}).then((res) => {
return fs.promises.readFile('./some-3.txt');
// handle success - 2
}).then((res) => {
// handle success - 3
}).catch((err) => {
console.log(err);
// handle error
});
const main = async () => {
try {
const res = await fs.promises.readFile('./some-file.txt');
console.log(res)
// handle success
} catch(err) {
console.log(err);
// handle error
}
}
进一步阅读-
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句