Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const { Client } = require('pg')
- const fs = require('fs')
- const local_file = require('./your_json_data.json')
- class Postgres {
- constructor() {
- this.client = new Client({
- user: 'postgres',
- host: 'xx.xxx.xxx.xx',
- database: 'postgres',
- password: 'password',
- port: xxxx,
- })
- this.client.connect()
- }
- async query(sql) {
- try {
- const { rows } = await this.client.query(sql)
- return rows
- } catch (err) {
- throw err
- }
- }
- }
- async function run() {
- const postgres = new Postgres()
- const makeVal = (val)=>{
- if(val === undefined) {
- return "'\"[undefined]\"'"
- } else {
- return "'" + JSON.stringify(val).replace(/'/g, "''") + "'"
- }
- }
- const makeVals = (objs) => {
- return objs.map((obj) => makeVal(obj)).join(',')
- }
- for(let k of Object.keys(local_file)) {
- try {
- const query = `INSERT INTO your_table (
- id,
- title,
- category,
- author,
- published_at,
- images,
- )
- VALUES(` + makeVals([
- k,
- local_file[k].title,
- local_file[k].type,
- local_file[k].author,
- local_file[k].publishedAt,
- local_file[k].attachments.images,
- ]) + ')'
- console.log(query)
- postgres.query(query)
- } catch(err) {
- throw err
- }
- }
- }
- run()
Add Comment
Please, Sign In to add comment