【问题标题】:Create new json from source json file in test project在测试项目中从源 json 文件创建新的 json
【发布时间】:2021-01-28 05:40:18
【问题描述】:

更新 我一直在努力解决这个问题并拥有以下代码 - st

  async generatejobs() {
    const fs = require("fs");
    const path = require("path");
    const directoryPath = path.join(__dirname, "../data/pjo/in");

    fs.readdir(directoryPath, function (err, files) {
      if (err) {
        console.log("Error getting directory information." + err);
      } else {
        files.forEach(function (file) {
          console.log(file);
          fs.readFile(file, (err, data) => {
            console.log(file); // this works, if I stop here
            // if (err) throw err;
            // let newJson = fs.readFileSync(data);
            // console.log(newJson);
          })
          // let data = fs.readFileSync(file);
          // let obj = JSON.parse(data);
          // let isoUtc = new Date();
          // let isoLocal = toISOLocal(isoUtc);
          // obj.printingStart = isoLocal;
          // obj.printingEnd = isoLocal;
          // let updatedFile = JSON.stringify(obj);
          // let write = fs.createWriteStream(
          //   path.join(__dirname, "../data/pjo/out", updatedFile)
          // );
          // read.pipe(write);
        });
      }
    });

只要我尝试取消注释下面显示的行,它就会失败。

let newJson = fs.readFileSync(data);

我得到的错误是这样的。

Uncaught ENOENT: no such file or directory, open 'C:\projects\codeceptJs\ipt\80-012345.json'

这是一个真实的陈述,因为路径应该如下。

'C:\projects\codeceptJs\ipt\src\data\pjo\in\80-012345.json'

我不明白为什么它在这里寻找文件,因为在代码的前面设置了路径并且似乎可以正常工作以通过这个找到文件。

const directoryPath = path.join(__dirname, "../data/pjo/in");

当前注释掉的其余代码是我尝试执行以下操作的地方。

  • 从源目录抓取每个文件
  • 放入json对象
  • 更新 json 对象以更改两个日期条目
  • 保存到我项目中的新 json 文件/新位置

原帖 我有一个 codeceptjs 测试项目,想在我的项目(src/data/jsondata/in)中包含一组现有的 json 文件,然后更新每个文件中的日期属性并将它们写入我的项目中的输出位置(src/数据/json数据/输出)。我需要更改日期,然后将其恢复为非常特定的字符串格式,我已完成此操作,然后将其插入到正在创建的新 json 中。我在那里完成了大约 80% 的工作,然后在尝试将文件从项目中的一个文件夹获取到另一个文件夹时遇到了问题。

我把它分成两部分。

  1. 获取日期并将其转换为我需要的日期字符串的函数

  2. 获取源 json、更新日期并在新文件夹位置创建新 json 的功能

1 号工作正常。 2 号不是。

如果有更好的方法来实现这一点,我非常愿意。

这是我尝试更新 json 的代码。这里的主要问题是我不理解和/或正确处理连接路径的东西。

generatePressJobs() {
    //requiring path and fs modules
    const path = require('path');
    const fs = require('fs');
    //joining path of directory
    const directoryPath = path.join(__dirname, '../', 'data/pjo/in/');
    //passsing directoryPath and callback function
    fs.readdir(directoryPath, function (err, files) {
      //handling error
      if (err) {
        I.say('unable to scan directory: ' + err);
        return console.log('Unable to scan directory: ' + err);
      }
      //listing all files using forEach
      files.forEach(function (file) {
        // Update each file with new print dates
        let data = fs.readFileSync(file);
        let obj = JSON.parse(data);
        let isoUtc = new Date();
        let isoLocal = toISOLocal(isoUtc);
        obj.printingStart = isoLocal;
        obj.printingEnd = isoLocal;
        let updatedFile = JSON.stringify(obj);
        fs.writeFile(`C:\\projects\\csPptr\\ipt\\src\\data\\pjo\\out\\${file}`, updatedFile, (err) => {
          if (err) {
            throw err;
          }
        });
      });
    });
  },

收到错误

Uncaught ENOENT: no such file or directory, open '80-003599.json'
      at Object.openSync (fs.js:462:3)
      at Object.readFileSync (fs.js:364:35)
      at C:\projects\codeceptJs\ipt\src\pages\Base.js:86:23
      at Array.forEach (<anonymous>)
      at C:\projects\codeceptJs\ipt\src\pages\Base.js:84:13
      at FSReqCallback.oncomplete (fs.js:156:23)

生成json的函数位于src/pages/basePage.js

我为json文件建立的文件夹结构位于 src/data/jsondata/in --> 用于原始源文件 src/data/jsondata/out --> 更改后生成的 json

任何见解或建议将不胜感激。

谢谢你, 鲍勃

【问题讨论】:

  • 现在会发生什么?有什么错误吗?

标签: javascript codeceptjs


【解决方案1】:

我的方法/解决方案 传递我在事件中采取的最终方法,这对其他人有帮助。中间的数据是特定于我的要求的,但留下来显示我做我需要做的事情的过程。

async generatePressjobs(count) {
    const fs = require("fs");
    const path = require("path");
    const sourceDirectoryPath = path.join(__dirname, "../data/pjo/in/");
    const destDirectoryPath = path.join(__dirname, "../data/pjo/out/");

    for (i = 0; i < count; i++) {
      // read file and make object
      let content = JSON.parse(
        fs.readFileSync(sourceDirectoryPath + "source.json")
      );

      // Get current date and convert to required format for json file
      let isoUtc = new Date();
      let isoLocal = await this.toISOLocal(isoUtc);
      let fileNameTimeStamp = await this.getFileNameDate(isoUtc);

      // Get current hour and minute for DPI time stamp
      let dpiDate = new Date;
      let hour = dpiDate.getHours();
      let minute = dpiDate.getMinutes();
      dpiStamp = hour + '' + minute;

      // update attributes in the json obj
      content.batchid = `80-0000${i}`;
      content.id = `80-0000${i}-10035-tcard-${dpiStamp}-0101010000_.pdf`
      content.name = `80-0000${i}-8.5x11CALJEF-CalBody-${dpiStamp}-01010100${i}_.pdf`;
      content.printingStart = isoLocal;
      content.printingEnd = isoLocal;

      // write the file
      fs.writeFileSync(
        destDirectoryPath + `80-0000${i}-SOME-JOB-NAME-${dpiStamp}.pdf_Press Job printing end_${fileNameTimeStamp}.json`,
        JSON.stringify(content)
      );
    }
  },

【讨论】:

    猜你喜欢
    • 2021-06-25
    • 2019-11-02
    • 1970-01-01
    • 2023-03-08
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多