NodeJS 如何访问Qwik终端中的文件系统?

pokxtpni  于 2023-06-29  发布在  Node.js
关注(0)|答案(2)|浏览(115)

我试图在Qwik中创建一个需要访问文件系统的端点。我打算使用Node.js fs来实现这个目的。
我是这么写的

import fs from 'fs'

我得到这个错误:

(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

如果我把它改为const fs = require('fs'),我会得到这个错误:

require is not defined

所以我被困在这里了。我该怎么办?

iyzzxitl

iyzzxitl1#

您能提供更多关于您希望如何使用文件系统的代码吗?
例如,您可以这样编写loader。该加载器被放置在routes文件夹中,并且在文件导入的顶部正常工作。

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..."
  }
});
7hiiyaii

7hiiyaii2#

下面是创建此端点的工作示例 http://xxx/API/config/
要读取的文件:'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));
};

顺便说一句,对于一个简单的JSON,你可以用公共目录来提供它。

相关问题