Reputation: 287
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
Upvotes: 7
Views: 20701
Reputation: 9611
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)
Upvotes: 2
Reputation: 5200
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()
.
Upvotes: 4
Reputation: 815
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
Upvotes: 10