Json "require" converted to Module "require" when installing packages - javascript

So... Lets say you have this library you want to post to NPM.
You convert it to a module type and use:
import {createRequire} from "module";
const require = createRequire(import.meta.url);
To implement require onto it. As you may know require can be used to read JSONs. So you try to read a json. Everything works fine when you test it onto a local machine. When you try linking it tho and you try to call that function it throws:
Error: Cannot find module 'something.json'
Is this an on going npm issue and if so how can i avoid it? Is there another way to read JSONs other than reading them as a txt file (which isn't very practical)?

Related

Having trouble converting this require statement into an import statement

I have a require statement in my script.
const packageJsonVersion = require('../package.json').version;
If I try and run the script I get an error saying I need to convert it to an import statement.
I changed the code to import { version as packageJsonVersion } from '../package.json' but when I run the script I get the following error.
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for /home/alex/_code/connect/package.json
I'm not sure how to get around this.
It depends on what environment you're doing this in.
Right now, browsers don't natively support JSON modules (though it's coming).
If you're doing this with a bundler, you need to be sure to tell the bundler how to handle the .json extension.
If you're doing this in Node.js, you need the JSON module notation (assert {type: "json"}).
Separately, though, JSON modules won't support named exports (this is mentioned by both links above). You'll have to import the default and then use the version property on it:
import data from "../package.json" assert { type: "json" };
const packageJsonVersion = data.version;

Import JSON file in NodeJs using es6

Hi i'm currently learning nodejs and I try to import a json file like this :
'use strict'
import data from 'users.json'
console.log(data)
Each time I get this error "Cannot find package 'users.json'"
But if I read the file with fs it worked so can you explain me how to do please
try :
import data from './users'
which is the es6 method of doing things or if you want an older syntax method you can try
const data = require('./users')
Okay so the explanation just is this, those fullstops and forward slash are used to indicate relative paths to the file the import is being called from, which means somethings you'd see something like for example ../file/help. The ./ means go up one directory ../ means go up two directories and so on. The name after the slash just tells your program the folder to go in to look for the file to import from so ./folder means go up one directory and enter into the folder directory and so on.
Almost forgot to mention, you should not import from a json file or a text file or any other file that does not have a .js extention(of which you do not actually have to specify) unless absolutely neccessary. To deal with files in node you have to use the fs library.
const fs =require('fs')
....
fs.readFile('./users.json','utf-8',(err,jsonString)=>{
const data = JSON.parse(jsonString);
//whatever other code you may fanacy
}
take a look at the fs module for a list of awesome features you can use to play with files
While the selected answer is correct, here's an explanation that I hope might add some clarity:
import MyModule from 'some-module'
is ES6 import syntax, as opposed to the older CommonJS syntax, which uses require.
CommonJS's require can be used to import files generally; ES6's import statement is more specific, and is generally used for importing js files which meet the criteria for being a module (having an export statement), or specific assets such as CSS sheets. Unlike require, it won't generally work for reading in files that are not modules.
You can't mix CommonJS require and ES6 import in the same file (at least not easily), so if you're using ES6 import and wish to read a file, do so with fs.readFileSync or a similar method. If the file is a json string, you'll need to parse it with JSON.parse().
If you want to use ES6 (NOT CommonJS) module system but want to use the Node.js version which is less than V18 (supports direct json import) then use the below approach.
import { createRequire } from "module";
const require = createRequire(import.meta.url); // construct the require method
const data = require("users.json"); // Now you can use require method in ES6
console.log(data)

how to import a standalone module build with browserify?

My question is how do I achieve importing a standalone module obtained with browserify, inside another javascript file. Here are some specific details:
I created a standalone module with browserify like this:
browserify module.js --s module_name > output.js
The file module.js contains at the end the line
module.exports = module_name;
Inside a file "use_module.js", I can now use the module module_name, with this code in some html file:
<sctipt src="output.js">
<sctipt src="use_module.js">
But what I would like is to specify just the script "use_module.js" in my html file, and somehow import "output.js" inside "use_module.js" directly in the javascript code. I tried two different approaches :
I tried javascript import module_name from './output.js' inside use_module.js, but then it cannot find the module module_name. Somehow I'm not sure module.exports is the same as export, neither with what browserify does with my module.exports anyway. (I'm very confused about all that).
I tried with require(./output.js) and then re-using browserify, but I then get a lot of weird errors with browserify, about tons of missing modules. Maybe I should specify some module informations in a file next to "output.js", that browserify can process, but I don't know really.
I understood what was failing in both approaches :
As I thought, import works only with export and not modules.exports. Also I read that browserify cannot work with the import/export syntax which is still too new.
More interestingly : a browserified file contains plenty of require(...) calls, which refers to a function created by browserify, and not to the CommonJS require keyword. Of course browserify does not know the difference, and thus look for tons a module to import a second time. All that needs to be done is to rename the word "require" into something else, and browserify can be applied a second time...
I however do not find my answer completely satisfactory : there must be a proper way to do this...

Require is not working for node-opcua

I want to load a local version of node-opcua with 'require' inside a HTML file, but it does not really work. The code snippet is the following:
<script type="text/javascript" src="path_to_require.js"></script>
<script>
var opcua = require(["path_to_node-opcua"]); <!-- Yes, the path is correct >
var client = new opcua.OPCUAClient();
...
When I execute the script I get the following error in the console:
Uncaught TypeError: opcua.OPCUAClient is not a constructor
Hence, var opcua is loaded correctly, but OPCUACluent is not, although the class is declared in a file that is present in the node-opcua folder called opcua_client.js under node-opcua\lib\client\
Sources:
The 'require' script from http://requirejs.org/docs/download.html#requirejs.
The node-opcua folder with the console command
npm install node-opcua.
node-opcua is not intended to run inside a browser as it relies on nodejs specific features such as filesystem access, crypto and so on.
You need to use browserify if you want to use that module in client. You will also need to look at how to use browserify with file system access (it can be done if paths are known ahead of time).

readFileSync is not a function

I am relatively new to Node.js and have been looking around but cannot find a solution. I did check the require javascript file and it does not seem to have a method for "readFileSync". Perhaps I don't have a proper require file? I had a hard time finding this file, everywhere talked about it but most people did not post where to get it.
I installed Node.js and have the require.js file. My current code is like this:
fs = require(['require'], function (foo) {
//foo is now loaded.
});
console.log("\n *STARTING* \n");
// Get content from file
var contents = fs.readFileSync("sliderImages", 'utf8');
I had a bit at first getting require to work however it seems to load the require JavaScript file. I have been following guides and I am not sure why I get this error:
Uncaught TypeError: fs.readFileSync is not a function
I have tried many fixes and cannot seem to figure this one out.
Node.js does not use Require.js. Require.js was built so that you could have asynchronous module loading on the client-side (in your browser).
Node.js uses CommonJS style modules. Your code using CommonJS would look like this:
var fs = require('fs');
console.log("\n *STARTING* \n");
var contents = fs.readFileSync("sliderImages", "utf8");
If we assume you saved this in a file called main.js you would then enter this command in your console (make sure you are in the same directory as the file):
node main.js
This code will not run in the browser. Node.js runs on the server. If you want to load a JSON file on the browser side then you'll need to load it using AJAX. There are numerous resources available to show you how to do this. Be aware that you must either run your page from a server or have a special flag enabled to load in files from the file system.
This error can arise if you write
const fs = import('fs');
in a Node module
but should write
import fs from 'fs';

Categories

Resources