gpt4 book ai didi

node.js - Nodejs 命令行应用程序 : unexpected token `else'

转载 作者:太空宇宙 更新时间:2023-11-03 22:17:30 24 4
gpt4 key购买 nike

我正在尝试创建一个 Node 命令行应用程序。我正在做的是从充满信息的文档中提取电子邮件。

但是当我运行命令 npm link 以使脚本全局可用时,我收到以下错误:

/c/Users/petfle/AppData/Roaming/npm/email-extract: line 11: syntax error near unexpected token `else'
/c/Users/petfle/AppData/Roaming/npm/email-extract: line 11: `else '

我的代码通过了 linting,我看不到任何错误。我是 Node 新手,所以这可能是一些简单的、 Node 特定的东西,我没有看到。

这是我的代码:

#!/c/Program\ Files/nodejs/node

var file_stream = require('fs');

var source = process.argv[2];
var output = process.argv[3];

file_stream.readFile(source, 'utf8', function (error, data) {
var list_of_emails = extract_emails(data);
write_to_file(list_of_emails);
});

function extract_emails(data) {
return data.match(/([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/g);
}

function write_to_file(emails) {
file_stream.writeFile(output, emails.join('\n'), 'utf8', function (error) {
console.log('Wrote ' + emails.length + ' lines to ' + output);
});
}

编辑:如果我删除 shebang 并使用 node myscript.js file.txt file2.txt 运行它,它就会起作用。我在 Windows 上。

编辑2:我正在 Git Bash 中运行它。即使在 Windows 上,它也可以使用 shebang 运行一个更简单的脚本。

最佳答案

在删除 shebang 行并通过以下方式调用它之后,它可以在 Linux Mint 15 中运行:

$ node code.js emails emailsOut

还添加了特定于操作系统的行 #!/usr/bin/nodechmod +x code.js 我可以通过运行它

$ ./code.js emails emailsOut

不幸的是,Windows 不支持 shebang 行。可以找到解决方法 here .

关于node.js - Nodejs 命令行应用程序 : unexpected token `else' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21208583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com