1

I'm trying to create an Endpoint in Qwik that needs to access file system. I intend to use Node.js fs for this purpose.

Here's what I wrote:

import fs from 'fs'

And I get this error:

(node:248) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/Project/SiteQwik/Run.js:1
import fs from 'fs'
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at internalCompileFunction (node:internal/vm:73:18)
    at wrapSafe (node:internal/modules/cjs/loader:1178:20)
    at Module._compile (node:internal/modules/cjs/loader:1220:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
    at Module.load (node:internal/modules/cjs/loader:1119:32)
    at Module._load (node:internal/modules/cjs/loader:960:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47

And if I change it to const fs = require('fs') I get this error:

require is not defined

So I'm stuck at this point. What should I do?

Ali EXE
  • 853
  • 1
  • 7
  • 21
  • Does this answer your question? [(node:9374) Warning: To load an ES module, set "type": "module"](https://stackoverflow.com/questions/63588714/node9374-warning-to-load-an-es-module-set-type-module) – Marc Jun 27 '23 at 11:35

2 Answers2

1

Here is a working example to create this endpoint http://xxx/api/config/

file to read: 'data/config.json'

{
  "version": "1"
}

endpoint: 'src/routes/api/config/index.tsx'

import { type RequestHandler } from '@builder.io/qwik-city';
import { readFileSync } from 'fs';

export const onGet: RequestHandler = async ({ json }) => {
    const path = './data/config.json';
    const config = readFileSync(path, { encoding: 'utf-8' });
    json(200, JSON.parse(config));
};

btw for a simple json you can serve it with the public directory

Giorgio Boa
  • 341
  • 4
0

Could you provide more code on how exactly you want to work with the file system?

For example, you can write loader as such. That loader is placed in the routes folder, and at the top of the file import works normally.

import { readFile } from "node:fs/promises"
export const useStaticTextLoader = routeLoader$(async () => {
  try {
    const someTextFromFile = await readFile(YOUR_PATH, { encoding: "utf-8" });

    return someTextFromFile;
  } catch (e) {
    console.log(e);

    return "FALLBACK..."
  }
});
stepeusz
  • 82
  • 5