Cannot resolve 'fs' on static generate project - javascript

I want to serve static file in my Next.js app and it is throwing me an error each time it wants to use import fs from 'fs';
I'm supposed not obligated to yarn add fs in order to use fs, why is it giving me this?
My next.config.js is pretty much empty:
const nextTranslate = require('next-translate');
module.exports = {
...nextTranslate(),
};
My current dynamic post page is:
/** #format */
import fs from 'fs';
export default function Doc() {
return <div>Enter</div>;
}
export const getStaticPaths = async () => {
return {
paths: [],
fallback: false,
};
};
Still I get this error:
I even tried to start a new project and it fails too once I try to use fs. Does it needs to be installed globally in my computer? I have node (v14.15.1) installed for sure.

fs is a module that is built into Node.js and depends on Node.js APIs.
It cannot run in a browser. So it cannot run in a typical React component.
You can use it in a server-side only module in Next.js but if you want to use it in a component then you'll probably need to replace it with an HTTP module like Axios and write a server-side endpoint to request your data from.

Related

Require does not work. What is this issue?

I'm installing this package in a super simple javascript nodejs file:
https://github.com/mafintosh/csv-parser
My code is like this:
const fs = require('fs');
const csv = require('csv-parser');
const stripBom = require('strip-bom-stream');
fs.createReadStream('data.csv')
.pipe(stripBom())
.pipe(csv())
...
ERROR:
Error [ERR_REQUIRE_ESM]: require() of ES Module node_modules\strip-bom-stream\index.js from app.js not supported.
Instead change the require of index.js in app.js to a dynamic import()
which is available in all CommonJS modules.
I use require everywhere. Why is it failing on this package? Also if I try to use import I get Cannot use import statement outside a module

Cannot import Node, JS, or Electron library in Angular Typescript module no matter what I try

I'm fairly new to stack overflow, so if I don't ask the question correctly feel free to help me out.
I've scoured every stack overflow and google article I can find and nothing works to import Electron, any other Node modules, or any native JS modules--I can only import and use Angular/typescript modules. I'm trying to import electron and use it in an angular app. I am also trying to use __dirname. For electron I've tried:
const { remote } = require('electron');
const { remote } = (<any>window)require('electron');
import { ipcRenderer, BrowserWindow, electron } from 'electron';
import * as remote from '#electron/remote'
For __dirname I've tried:
import * as fs from 'fs';
import { readFileSync } from 'fs';
import readFileSync from 'fs';
and for the implementation:
import.meta.url
process.cwd()
__dirname //worth a shot I guess
I've combined these options, and nothing works. I've run npm install --save-dev #types/node, and when that didn't work tried deleting the node_modules folder and ran npm install. "types": ["node"] has already been added to tsconfig.json's compilerOptions.
Here is one of my errors:
Error: src/app/electron/electron.service.ts:3:20 - error TS2591: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i --save-dev #types/node` and then add `node` to the types field in your tsconfig.
3 const { remote } = require('electron');
~~~~~~~
I've already installed #types/node. It also almost always posts the following error. I have no clue what it's for, as it shows even when I'm not importing 'fs'.
Error: ./node_modules/electron/index.js
Module not found: Error: Can't resolve 'fs' in '/Users/user/Programming/Git/project/node_modules/electron'
resolve 'fs' in '/Users/user/Programming/Git/project/node_modules/electron'
Parsed request is a module
using description file: /Users/user/Programming/Git/project/node_modules/electron/package.json (relative path: .)
Field 'browser' doesn't contain a valid alias configuration
resolve as module
looking for modules in /Users/user/Programming/Git/project
using description file: /Users/user/Programming/Git/project/package.json (relative path: .)
Your browser cannot run modules written in C++ like fs and electron. Node.js can do it because node developers specifically created node to be able to load binary modules (written in C++). Browsers can only run javascript modules.
As such builders such as Webpack ignore these modules simply because it does not make sense to include them.
You cannot use fs and electron in your Angular app. You can however use Angular in your electron app (because electron was created to run javascript code and Angular compiles to pure javascript code).
Trying to use fs or electron in Angular is a little bit like trying to import Internet Explorer or Adobe Photoshop in Angular.

How Can I Use Named Module Exports in Node 16 App?

I'm using Node 16.3.0 and Express 4.17.1 (though my Node version is flexible)
I have a session.js file that's like this:
// session.js
exports.fetchUserId = async function(token){
...
}
exports.save = async function(userId){
...
}
Then over in my app.js file, I try to do this:
// app.js
import session from './session.js'
I get the following error:
import session from './session.js'
^^^^^^^
SyntaxError: The requested module './session.js' does not provide an export named 'default'
...and then I want to use session in app.js like this:
let userId = await session.fetchUserId(req.body.token)
I have tried the following without any luck:
Adding "type": "module" to package.json
This answer by doing npm i esm
Using nodemon --experimental-modules app.js
My code works fine when used in a NuxtJS project, but I'm trying a vanilla Node/Express app and the named exports don't work.
Any idea what I'm doing wrong?
Problem in your code is that you are mixing the ES modules with CommonJS modules.
By default, node treats each javascript file as a CommonJS module but with the following in the package.json file
"type": "module"
you are telling node to treat each javascript file as a Ecmascript module but in session.js file, you are using the CommonJS module syntax to export the functions.
Solutions
You could solve your problem using one of the following options:
Change the extension of the session.js file to .cjs. (Don't forget to change the extension in the import statement in app.js file as well).
Changing the extension to .cjs will tell node to treat session.cjs file as a CommonJS module.
Just use ES modules and change the exports in session.js file as shown below:
export const fetchUserId = async function(token){ ... }
export const save = async function(userId) { ... }
and change the import statement in app.js file as:
import * as session from "./session.js";

Build Vue application to support Server Side Rendering on NodeJS

I am building a Vue Application with Nuxt. I have built with SSR mode. It builds server-side build with entry point .Nuxt/server.js.
I am using https://ssr.vuejs.org/api/#createbundlerenderer to create renderer on NodeJS, so I can provide template Html with the component inside and it will be able to render that component. But the problem is server.js is using import statements to import modules which is not working with NodeJS.
(function (exports, require, module, __filename, __dirname) { import { stringify } from '...'
^^^^^^
SyntaxError: Cannot use import statement outside a module
I tried to set "type": "module" in the package.json or use the .mjs extension. But, had no luck with that.
Here is the generated server build.
import { stringify } from 'querystring'
import Vue from 'vue'
import fetch from 'node-fetch'
import middleware from './middleware.js'
...
Here is the code I have used to render above generated build.
const { createBundleRenderer } = require('vue-server-renderer');
const renderer = createBundleRenderer('/ABSOLUTE_PATH/.nuxt/server.js');
renderer.renderToString().then(html => console.log(html)).catch(e => console.error(e));
Can anyone please help me to generate Node-style server bundle?

Cannot find meteor module

I am trying to run a meteor app but keep getting the Cannot find module error when I try to import one of my files.
My folder directory:
/app/client/imports/api/tasks.js
/app/server/main.js
In my main.js I am trying to import tasks.js:
import '../client/imports/api/tasks.js';
This throws the error Error: Cannot find module '../client/imports/api/tasks.js'.
My tasks.js:
import { Mongo } from 'meteor/mongo';
export const Tasks = new Mongo.collection('tasks');
Does anyone know what might be going on?
You can't import a /client based file from the /server side. Files stored under a client directory are only bundled and made available to the client side of the application (the part that runs in a users browser). Files stored under a server directory are only bundled and made available on the server side, running via Node.
Get rid of the /client prefix from your tasks.js reference, to be able to reference the import from both sides. For example:
/app/imports/api/tasks.js
import { Mongo } from 'meteor/mongo';
const Tasks = new Mongo.Collection('tasks');
export default Tasks;
Then in /app/client/main.js or /app/server/main.js, you could reference the tasks.js file like:
import Tasks from '/imports/api/tasks.js';
The problem is in file structure.
Your imports/ folder should be on the same level with client/ and server/.

Categories

Resources