我遇到的问题是,当我需要library all-the-cities时,reactjs无法工作,并返回以下错误:
TypeError: fs.readFileSync is not a function
(anonymous function)
C:myproject/node_modules/all-the-cities/index.js:6
3 | const path = require('path')
4 |
5 |
> 6 | var pbf = new Pbf(fs.readFileSync(path.join(__dirname, 'cities.pbf')))
7 |
8 |
9 | console.log(pbf);
View compiled
./node_modules/all-the-cities/index.js
http://localhost:3000/static/js/0.chunk.js:50:30
这个库在我的其他nodejs项目中工作。 我测试了它的执行情况:
console.log(typeof fs.readFileSync(path.join(__dirname, 'cities.pbf')))
它说它是一个目标,我还是不明白问题出在哪里。 如果需要的话,这是整个index.js文件:
const Pbf = require('pbf')
const fs = require('fs')
const path = require('path')
var pbf = new Pbf(fs.readFileSync(path.join(__dirname, 'cities.pbf')))
console.log(pbf);
var cities = []
var lastLat = 0
var lastLon = 0
while (pbf.pos < pbf.length) {
cities.push(pbf.readMessage(readCity, {
cityId: '',
name: '',
altName:'',
country: '',
featureCode: '',
adminCode: '',
population: 0,
loc: {
type: 'Point',
coordinates: [0, 0] //[lon,lat]
}
}))
}
module.exports = cities
function readCity(tag, city, pbf) {
if (tag === 1) city.cityId = pbf.readSVarint()
else if (tag === 2) city.name = pbf.readString()
else if (tag === 3) city.country = pbf.readString()
else if (tag === 4) city.altName = pbf.readString()
else if (tag === 5) city.muni = pbf.readString()
else if (tag === 6) city.muniSub = pbf.readString()
else if (tag === 7) city.featureCode = pbf.readString()
else if (tag === 8) city.adminCode = pbf.readString()
else if (tag === 9) city.population = pbf.readVarint()
else if (tag === 10) {
lastLon += pbf.readSVarint()
city.loc.coordinates[0] = lastLon / 1e5
} else if (tag === 11) {
lastLat += pbf.readSVarint()
city.loc.coordinates[1] = lastLat / 1e5
}
}
这是我正在使用的代码:
import React, { Component } from "react";
import './textFieldCity.sass';
const cities = require('all-the-cities');
class App extends Component {
change = input => {
};
render() {
return (
<div className="field">
<form id={this.props.formID}>
<label for={this.props.inputName}>{this.props.labelText}</label>
<input onChange={this.change} type="text" name={this.props.inputName}/>
</form>
</div>
);
}
}
export default App;
方法ReadFileSync
来自本机节点模块。 您可以在节点服务器中使用它,而不是在ReactJS中。 您应该从ReactJS代码对节点服务器进行AJAX调用,以访问本机节点模块中的方法