Search code examples
node.jsfilesystems

NodeJS. When creating a file using FS, the error Type Error


I tried JSON.stringify, .toString, not work.

Here is the code:

const astCode = (await fs.readFile(filename)).toString();
    const ast = JSON.parse(astCode);
    const jsCode = generate(ast);
    var jsFilename = makename(5);
    var jsFileNameEm = `${jsFilename}.js`;
    await fs.writeFile(jsFileNameEm, JSON.stringify(jsCode, null, 2), { encoding: "utf-8" });
    console.log(`Wrote ${jsFileNameEm}.`);

On startup, it throws an error:

TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined at writeFileSync (node:fs:2211:5) at main (sketch/src/parser/generator.js:28:11).

I am using readFileSync and writeFileSync from FS


Solution

  • I had a look at the code in git it had this :

         if (node.operation === "assign") {
        const varName = node.identifier.value;
        const value = node["value"].value; // SUCCESS 7:11 19 SEPTEMBER.
        return `let ${varName} = ${value};`;
           //return [`let ${varName} = ${value};`, `console.log(${varName})`];
          //return [(`let h = 0;`), (`let s = 2`)]
           }
    

    while it should be this :

         if (node[0].operation === "assign") {
        const varName = node[0].identifier.value;
        const value = node[0].value.value // SUCCESS 7:11 19 SEPTEMBER.
        return `let ${varName} = ${value};`;
        //return [`let ${varName} = ${value};`, `console.log(${varName})`];
       //return [(`let h = 0;`), (`let s = 2`)]
       }
    

    because most of the files seemed to contain a list of objects, and you were accessing object keys instead of array indexes first.

    PS : this

    node generator.js ./ast/9kME3.ast.json
    

    worked and returned this:

    Wrote kAEie.js.
    

    inside that file :

    let s = 3 + 3;