2016-11-23 7 views
1

nodejsのディレクトリにあるすべてのjsonファイルをマージしたいと思います。ファイルはユーザーによってアップロードされていて、私が知っているのはその名前がデバイスの "count" .jsonだということです。毎回カウントが増分されます。私はjson-concatについて知っていますが、ディレクトリ内のすべてのファイルをマージするためにどのように使用しますか?すべてのjsonファイルをディレクトリnodejsにマージ

jsonConcat({ 
    src: [], 
    dest: "./result.json" 
}, function (json) { 
    console.log(json); 
}); 

答えて

2

あなたは慎重にdocsを読めば、あなたはこの部分が表示されます:オプションが渡されたオブジェクト

は、次のキーがあり:

:ので、ここで

src: 
    (String) path pointing to a directory 
    (Array) array of paths pointing to files and/or directories 
    defaults to . (current working directory) 
    Note: if this is a path points to a single file, nothing will be done. 

は修正です

1)jsonファイルを具体的なパスに移動します。

2)は、このコードをチェック:

jsonConcat({ 
    src: './path/to/json/files', 
    dest: "./result.json" 
}, function (json) { 
    console.log(json); 
}); 

here is the prove how it uses src paramはほとんどそれだけで3番目の部分のパッケージを使用していない開発者から必要とするだけでなく、それのソースに飛び込みます。

要約:KISS(:

2

あなたはディレクトリ内のファイルを読み込んでjson-concatにそれらを渡すためにfsモジュールを使用することができます。

const jsonConcat = require('json-concat'); 
const fs = require('fs'); 

// an array of filenames to concat 
const files = []; 

const theDirectory = __dirname; // or whatever directory you want to read 
fs.readdirSync(theDirectory).forEach((file) => { 
    // you may want to filter these by extension, etc. to make sure they are JSON files 
    files.push(file); 
} 

// pass the "files" to json concat 
jsonConcat({ 
    src: files, 
    dest: "./result.json" 
}, function (json) { 
    console.log(json); 
}); 
関連する問題