【问题标题】:JSON object not being passed to functionJSON对象未传递给函数
【发布时间】:2017-05-01 02:30:44
【问题描述】:

我有一个允许上传 csv 文件的应用程序,通过 csvtojson 将 csv 转换为 json,然后通过 mongoose 将 json 导入 mongo db。

这大部分都有效,但由于某种原因,我无法让导入脚本动态获取新生成的 json,但我可以硬编码 json 的路径。

我有一个看起来像这样的转换脚本,并且似乎正在正确地完成它的工作(即在上传文件时调用它,将 csv 转换为 json,然后删除上传的 csv)

var convertJSON = function convertJSON(inputFile, callback) {


var fs = require('fs');
const csv=require('csvtojson');
console.log('NOW I AM IN convertJSONOriginal');

const converter=csv({
    noheader:true,
    headers: ['date','vendor','amount'],
    trim:false
})
    .fromFile('./data/' + inputFile,function(err,result){
        // if an error has occured then handle it
        if(err){
            console.log("An Error Has Occurred");
            console.log(err);
        }
        // create a variable called json and store
        // the result of the conversion

        //var json = result;
        var json = JSON.stringify(result);

        fs.writeFile('./data/' + inputFile.split('.')[0] + '.json', json, function(err) {
            if(err) {
                return console.log(err);
            }

            console.log("The file was saved!");
            //TODO delete the imported csv file
            fs.unlink("./data/" + inputFile, function (err) {
                if (err) {
                    console.log("failed to delete local file:"+err);
                } else {
                    console.log('successfully deleted local file');
                }
            });
            var jsonFile = inputFile.split('.')[0] + '.json' ;
            console.log('THIS IS jsonfile AS IT COMES FROM convertJSONOriginal' +jsonFile);
            callback(err,jsonFile);
        });

    });
};


module.exports = {
convertJSON: convertJSON
};

我有一个调用这个函数的 upload.js 路由

var express = require("express");
var multer = require('multer');
var router = express.Router();
var path = require('path');
var runScript = require('../helpers/runScript');
var convertJSON = require('../helpers/convertJSONOriginal');
var upload = require('../helpers/statement-seeder');

/*
  The below hardcoded path will allow the call to console.log('AND THIS 
 WITH statements '+JSON.stringify(statements));
  to print out an object
*/

 var statements= require("../data/HSBC-1493565387017.json");

var storage = multer.diskStorage({
  destination: function(req, file, callback) {
      callback(null, './data')
  },
  filename: function(req, file, callback) {
    callback(null, req.body.bank + '-' + Date.now() + 
path.extname(file.originalname))

  }
});


router.post('/',
  multer({
      storage: storage,
      fileFilter: function(req, file, callback) {
          var ext = path.extname(file.originalname)
          if (ext !== '.csv') {
              return callback(res.end('Only csvs are allowed'), null)
          }
          callback(null, true)
      }
  })
      .single('statement'), //this is the name of the form field to get the file from
function(req, res) {
    console.log('THIS IS THE FILENAME - '+req.file.filename);
    convertJSON.convertJSON(req.file.filename, function(err, filename){
        if (err){
            console.log(err);
        } else {
            //prints out AND THIS WITH ../data "../data/HSBC-1493565431073.json" to console

console.log('THIS IS WITH ../data '+JSON.stringify('../data/'+filename));
            //prints out AND THIS WITH data "/data/HSBC-1493565431073.json" to console

 console.log('AND THIS WITH /data '+JSON.stringify('/data/'+filename));
            //prints out AND THIS WITH ./data "./data/HSBC-1493565431073.json" to console

 console.log('AND THIS WITH ./data '+JSON.stringify('./data/'+filename));
            //prints out the json object to console

 console.log('AND THIS WITH statements '+JSON.stringify(statements));
            //upload.statementSeeder(filename);
            //upload.statementSeeder(statements);

        }
    });

});

module.exports = router;

所以基本上如果我来自硬编码var statements= require("../data/HSBC-1493565387017.json"); 的“console.log(statements)”(其中 ../data/HSBC-1493565387017.json 是一个已通过我编写的代码上传和转换的文件)然后我看到了完整的 json 对象,但是如果我从给定回调的值中进行 console.log,那么它只会打印文件的路径。

谁能告诉我我做错了什么?

编辑回答问题: 查看 filename 的 typeof(这是从 JSON 转换脚本传回的 req.file.filename,如果我的想法/代码正确,则上面上传的每个文件都不同) console.log('HERE IS THE TYPEOF for filename'+ typeof filename); 返回string。 但是console.log('HERE IS THE TYPEOF for statement'+ typeof statements); 其中statements 被硬编码为转换后的json 文件var statements= require("../data/HSBC-1493565387017.json"); 返回object 的实际位置。

【问题讨论】:

  • 试试console typeof语句..如果要读取文件内容,可以使用fs模块..
  • @thedarkcoder 谢谢。我已经对我的问题添加了编辑。获取动态生成的文件名时的typeofstring,而对于硬编码的文件名是object。但我不明白他们的演员阵容有何不同

标签: json node.js asynccallback


【解决方案1】:

好的,我已将以下内容添加到 convertjson 脚本中,该脚本现在将打开的 json 文件作为对象传递给回调

 var obj;
 fs.readFile('./data/' + inputFile.split('.')[0] + '.json', 'utf8', 
     function (err, data) {
       if (err) throw err;
         obj = JSON.parse(data);
                //console.log(obj);
                callback(err,obj);
       });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 2011-12-07
    相关资源
    最近更新 更多