简体   繁体   中英

How we can find a word in JavaScript without HTML in a file.txt?

In my project I tried to find some words in a file, I coded the program in JS, but I have some syntax problem and I don't know why. The goal is when the program finds "rose" it writes on the terminal "flower" etc. My program is :

var fs = require('fs');
var str = fs.readFileSync('input.txt', 'utf8');

str.split(/\s+/).forEach(s =>
  console.log(
    s === 'rose'
      ? 'flower'
      : s === 'bird'
      ? 'animal'
      : s === 'cookie'
      ? 'dog'
      : 'unknown'
  )
);

The different errors which appear on the terminal are :

  js: "prog.js", line 5: syntax error
js: str.split(/\s+/).forEach(s =>
js: ............................^
js: "prog.js", line 6: syntax error
js:   console.log(
js: ..........^
js: "prog.js", line 7: syntax error
js:     s === 'rose'
js: ........^
js: "prog.js", line 9: syntax error
js:       : s === 'bird'
js: .......^
js: "prog.js", line 11: syntax error
js:       : s === 'cookie'
js: .......^
js: "prog.js", line 13: syntax error
js:       : 'unknown'
js: .......^
js: "prog.js", line 15: syntax error
js: );
js: ^
js: "prog.js", line 1: Compilation produced 7 syntax errors.

And to run the program I use this command : rhino prog.js

So can you help me to find the error please?

You're getting the error because Rhino doesn't currently support arrow functions: ie () => { ...}

See: https://mozilla.github.io/rhino/compat/engines.html#ES2015-syntax-destructuring--parameters-defaults--arrow-function

You're in luck, this is an easy fix! Just remove the arrow function; this should work:

var fs = require('fs');
var str = fs.readFileSync('input.txt', 'utf8');

str.split(/\s+/).forEach(function (s) {
  return console.log(s === 'rose' ? 'flower' : s === 'bird' ? 'animal' : s === 
'cookie' ? 'dog' : 'unknown');
});

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