简体   繁体   中英

How do I require a node module in my client side javascript?

I am trying to build a natural language processing bot using javascript and jQuery for the logic and node and express as the framework. I discovered a natural language processing facility that would be extremely useful for my project https://github.com/NaturalNode/natural unfortunately the documentation is sparse and I have only been using node for a couple of weeks.

This is the code I have on my server side app.js

 var natural = require('natural'),
 tokenizer = new natural.WordTokenizer();
 stemmer.attach();
 var express = require("express");
 app = express();
 app.set("view engine", "ejs");
 app.use(express.static(__dirname + '/public'));

I am requiring the 'natural' module here but I am unable to use the methods that are outlined in the documentation.

var natural = require('natural'),
tokenizer = new natural.WordTokenizer();
console.log(tokenizer.tokenize("your dog has fleas."));
// [ 'your', 'dog', 'has', 'fleas' ]

The method 'tokenizer' is undefined. I have done quite a bit of research on this and looked into using module.export and passing variables through the app.get function for the index.ejs page I am using but I have been unsuccessful so far.

NOTE: The javascript file I am trying to use these methods in is located in the public/javascript directory while the app.js file is located in the main project directory. I have tried to require the 'natural' package directly in the javascript file I am trying to use the methods in but an error was thrown saying require is an undefined method.

here is the package.json file:

 {
  "name": "JSAIN",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
  "test": "echo \"Error: no test specified\" && exit 1"
 },
  "author": "",
  "license": "ISC",
  "dependencies": {
  "ejs": "^2.3.1",
  "express": "^4.12.3",
  "natural": "^0.2.1",
  "underscore": "^1.8.2"
    }
  }

也许您可以尝试使用browserify ,从而允许您在浏览器中使用某些npm模块。

Converting my comment into an answer...

The natural module says it's for running in the node.js environment. Unless it has a specific version that runs in a browser, you won't be able to run this in the browser.

have you install that module with global mode and have defined that in package.json? Otherwise, try this:

npm install -g natural

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM