Writing files in Node.js

前端 未结 19 2079
情歌与酒
情歌与酒 2020-11-21 11:57

I\'ve been trying to find a way to write to a file when using Node.js, but with no success. How can I do that?

19条回答
  •  我寻月下人不归
    2020-11-21 12:14

    Here is the sample of how to read file csv from local and write csv file to local.

    var csvjson = require('csvjson'),
        fs = require('fs'),
        mongodb = require('mongodb'),
        MongoClient = mongodb.MongoClient,
        mongoDSN = 'mongodb://localhost:27017/test',
        collection;
    
    function uploadcsvModule(){
        var data = fs.readFileSync( '/home/limitless/Downloads/orders_sample.csv', { encoding : 'utf8'});
        var importOptions = {
            delimiter : ',', // optional 
            quote     : '"' // optional 
        },ExportOptions = {
            delimiter   : ",",
            wrap        : false
        }
        var myobj = csvjson.toSchemaObject(data, importOptions)
        var exportArr = [], importArr = [];
        myobj.forEach(d=>{
            if(d.orderId==undefined || d.orderId=='') {
                exportArr.push(d)
            } else {
                importArr.push(d)
            }
        })
        var csv = csvjson.toCSV(exportArr, ExportOptions);
        MongoClient.connect(mongoDSN, function(error, db) {
            collection = db.collection("orders")
            collection.insertMany(importArr, function(err,result){
                fs.writeFile('/home/limitless/Downloads/orders_sample1.csv', csv, { encoding : 'utf8'});
                db.close();
            });            
        })
    }
    
    uploadcsvModule()
    

提交回复
热议问题